jQuery .addClass() add new style class to element

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 a  v a 2s .  c  o  m-->
              $("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





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities