How to add class of an element using jquery

How to add class of an element using jquery

It’s important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.

Before jQuery version 1.12/2.2, the .addClass() method manipulated the classNameproperty of the selected elements, not the classattribute. Once the property was changed, it was the browser that updated the attribute accordingly. An implication of this behavior was that this method only worked for documents with HTML DOM semantics (e.g., not pure XML documents).

As of jQuery 1.12/2.2, this behavior is changed to improve the support for XML documents, including SVG. Starting from this version, the classattribute is used instead. So, .addClass() can be used on XML or SVG documents.

More than one class may be added at a time, separated by a space, to the set of matched elements, like so:

1

$( "p" ).addClass( "myClass yourClass" );

This method is often used with .removeClass() to switch elements’ classes from one to another, like so:

1

$( "p" ).removeClass( "myClass noClass" ).addClass( "yourClass" );

Here, the myClass and noClass classes are removed from all paragraphs, while yourClass is added.

As of jQuery 1.4, the .addClass() method’s argument can receive a function.

1

2

3

$( "ul li" ).addClass(function( index ) {

return"item-" + index;

});

Given an unordered list with two <li> elements, this example adds the class “item-0” to the first <li> and “item-1” to the second.

Examples:

Add the class “selected” to the matched elements.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

<!doctype html>

<htmllang="en">

<head>

<metacharset="utf-8">

<title>addClass demo</title>

<style>

p{

margin:8px;

font-size:16px;

}

.selected{

color: blue;

}

.highlight{

background: yellow;

}

</style>

<scriptsrc="https://code.jquery.com/jquery-1.10.2.js"></script>

</head>

<body>

<p>Hello</p>

<p>and</p>

<p>Goodbye</p>

<script>

$( "p" ).last().addClass( "selected" );

</script>

</body>

</html>

Click here to see the details with an example https://api.jquery.com/addclass/

About Us

We are the creative team of designers. Our target is to provide templates, themes and plugin easily to developers and end users who can customize all the data and design from back-end and manage his/her site by themselves and also provide themes to you below the market rate. And we also provide customized templates to users on your order, you can place your order on request a quote page.