Add CSS Class Using jQuery

By bhagwatchouhan
Add CSS Class Using jQuery

The addClass function provided by jQuery can be used to add the single class or multiple classes as shown below.

// Add single class
jQuery( <selector> ).addClass( <class name> );
// Add multiple classes jQuery( <selector> ).addClass( <class1 class2 class3> );

A single class can be added by passing the class name as a function argument. We can also add multiple classes by passing the class names separated by space.

The HTML used for the examples is as shown below.

<div class="wrap-items">
	<div class="wrap-item">
		<div id="item-1" class="item has-banner">
			<!-- item element -->
		</div>
		<div id="item-2" class="item">
			<!-- item element -->
		</div>
	</div>
</div>

The below-mentioned examples show how we can add either single or multiple classes.

// Add the class has-price to the element having id item-1
// Note that we do not need to use dot(.) for the argument passed to addClass function
jQuery( '#item-1' ).addClass( 'has-price' );
// Remove and add class jQuery( '#item-1' ).removeClass( 'has-banner' ).addClass( 'has-gallery' );
// Add the classes has-price and has-image jQuery( '#item-1' ).addClass( 'has-price has-image' );

The more advanced usage is by passing a function as an argument to the addClass method as shown below.

jQuery( ".item" ).addClass( function( idx ) {
	return "item" + idx;
});

Share this blog:

Profile picture for user bhagwatchouhan
bhagwatchouhan