jQuery Tutorial Tutorials - jQuery .addClass() method

jQuery .addClass() method

The .addClass() method in jQuery is used to add class name(s) to matched elements.

jQuery .addClass() method Syntax

.addClass('className')
.addClass('className className')
.addClass(function)
Parameter Type Description
className String the class name to be added to the class-attribute of each matched element
funtion(index, oldClassName) Function a function returning one or more space-separated class names to be added.
index is the position of the element in the set.(based 0)
oldClassName is/are old class name(s).

.addClass('className')

example

Add the class "selected" to the matched elements.

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

Try now

.addClass('className className')

example

Add the mulitple class "selected1","selected2" to the matched elements.

$("p").addClass("selected1 selected2");

Try now

.addClass(function)

example

adds the class "item-0" to the first

  • and "item-1" to the second.

    HTML

    <ul>
          <li>Hello</li>
          <li>Hello</li>
          <li>Hello</li>
    </ul>
    

    jQuery

    $('ul li').addClass(function(index) {
        return "item-" + index;
    });
    

    Try it

  • Date:2019-08-19 15:56:47 From:www.Lautturi.com author:Lautturi