Cover Image for jQuery addClass() method
113 views

jQuery addClass() method

The jQuery addClass() method is used to add one or more CSS classes to the selected elements. It allows you to dynamically apply styles and effects to elements by adding classes to them.

The syntax for using the addClass() method is as follows:

$(selector).addClass(className);
  • selector: It is a string that specifies the elements to be selected.
  • className: It is a string or space-separated list of classes that you want to add to the selected elements.

Here’s an example of how you can use the addClass() method:

HTML:

<button id="myButton">Click Me</button>

JavaScript:

// Add the "btn" and "btn-primary" classes to the button element
$('#myButton').addClass('btn btn-primary');

In the above example, the addClass() method is used to add two classes, “btn” and “btn-primary,” to the button element with the ID “myButton.” As a result, the button will visually appear like a primary button styled using Bootstrap’s CSS framework (assuming the corresponding CSS styles are defined).

After using the addClass() method, the resulting HTML would look like this:

<button id="myButton" class="btn btn-primary">Click Me</button>

The addClass() method can also be used to add classes dynamically based on certain conditions or user interactions. For example:

// Add the "active" class to a menu item when it is clicked
$('.menu-item').click(function() {
  $(this).addClass('active');
});

In this example, when a menu item with the class “menu-item” is clicked, the addClass() method will add the class “active” to that specific menu item, visually indicating the active state.

You can also add multiple classes at once by passing a space-separated list of class names as the className parameter:

// Add multiple classes to an element
$('.my-element').addClass('class1 class2 class3');

The addClass() method is a powerful way to manipulate the appearance and behavior of elements on your web page dynamically. It is commonly used in combination with other jQuery methods and event handlers to create interactive and responsive user interfaces.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS