jQuery Tutorial : addClass() Method

preview_player
Показать описание

Lets take a look at the add Class method in jquery.
The addClass method in jQuery is used to add the specified class or classes to the required elements.
Please note that the addClass method will append new classes to specified elements and does not replace or remove the existing classes of an element.
Lets see an example.
lets write a class 'selected' which has a property 'color:blue'.
lets write a single paragraph in the html body.
We also have a button 'Click Me' on click of which we will be executing the javascript function 'myFunction'.
We see that the text gets highlighted on click of button because the function appends new class in to the paragraph.
Please note that if we have multiple paragraph elements in our html body, all of them will be highlighted blue.
Lets see an example.
If you would like to add the class only to a specific element, for example 2nd paragraph element, we can make use of something called nth child selector.
We can add multiple classes to an element by separating each class name with a space.
We can also write a function inside the addClass method which conditionally returns the required class by checking the index or current class of a specific element.
we are checking if index is equal to 2. In other words, if it is a second paragraph, we append the classes.
We can now remove the nth child selector as we are doing it inside the function by checking the index.
Рекомендации по теме