Add a Class to Your HTML with jQuery
this Article Is About Add a Class to Your HTML with jQuery makes it super easy to dynamically add a class or several classes to any HTML element’s using only one line of code and the .addClass() method. This trick can be really useful if you want to change the styling of a particular element depending on certain conditions, which you can define using jQuery code.
Add a class name to the first <p> element:
Let’s say you’d like to use jQuery to add a new class that will change the text to make it blue:
Your CSS class might look something like this:
2 color: blue;
To apply the .blue class to the p tag, you’ll want to use jQuery code that resembles the following:
And your results should look like this:
If you want a class addition to be contingent upon certain conditions, make sure you include the .addClass() code within an if statement or a function defining your desired conditions.
Definition and Usage
The addClass() method adds one or more class names to the selected elements.
This method does not remove existing class attributes, it only adds one or more class names to the class attribute.