.addClass()

Syntax and Description

  • .addClass(className)
    className: One or more class names to be added to the class attribute of each matched element
  • .addClass(function)
    function: A function returning one or more space-separated class names to be added

.addClass() method adds one or more classes to each element in the set of matched elements. More than one class may be added at a time, separated by a space, to the set of matched elements.

The following code add myClass yourClass for paragraph elements.

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

The .addClass() method allows us to set the class name by passing in a function.


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

Its return value is the jQuery object, for chaining purposes.

Add style for the last paragraph

The following code gets last paragraph and adds class.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  www . j  av  a 2s  .  com-->
              $("p:last").addClass("selected");

        });
    </script>
    <style>
       .selected { color:red; }
    </style>
  </head>
  <body>
    <body>
      <p>A</p>
      <p>B</p>
      <p>C</p>
  </body>
</html>

Click to view the demo

The code above generates the following result.

.addClass()
Home »
  Javascript Tutorial »
    jQuery Reference »
      DOM
...
$("html tags")
.add()
.addClass()
.after()
.andSelf()
.append()
.appendTo()
.attr()
.before()
.children()
.clone()
.closest()
.contents()
.css()
.detach()
.filter()
.first()
.get()
.has()
.hasClass()
.height()
.html()
.index()
.innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.is()
.last()
.map()
.next()
.nextAll()
.nextUntil()
.not()
.offset()
.offsetParent()
.outerHeight()
.outerWidth()
...