How To Add a Class to Your HTML with jQuery


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:

$(“button”).click(function(){
$(“p:first”).addClass(“intro”);
});

Let’s say you’d like to use jQuery to add a new class that will change the text to make it blue:

Screen Shot 2016-08-15 at 5.06.03 PM

Your CSS class might look something like this:

1 blue{

2 color: blue;

3. }

To apply the .blue class to the p tag, you’ll want to use jQuery code that resembles the following:

1 $(‘p’).addClass(‘blue’);

And your results should look like this:

Screen Shot 2016-08-15 at 5.06.13 PM

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.

 

Leave a Reply

Your email address will not be published. Required fields are marked *