Hi all, I am slightly confused about passing functions to the addClass method. This code is taken from the jquery.com site http://api.jquery.com/addClass/:

<!DOCTYPE html>
  div { background: white; }
  .red { background: red; }
  .red.green { background: green; }
  <script src="http://code.jquery.com/jquery-latest.js"></script>

 <div>This div should be white</div>
 <div class="red">This div will be green because it now has the "green" and "red" classes.
   It would be red if the addClass function failed.</div>
 <div>This div should be white</div>
 <p>There are zero green divs</p>

  $("div").addClass(function(index, currentClass) {
    var addedClass;

    if ( currentClass === "red" ) {
      addedClass = "green";
      $("p").text("There is one green div");

    return addedClass;


Couple of points:
1)how is the script called? There is no call, does it run on document load?
2)addClass(function(index, currentClass) {: what are these 2 parameters index and currentClass, where do they come from?
3)return addedClass; if they add this, does it mean that the whole expression gets the value of addedClass?


4 Years
Discussion Span
Last Post by Violet_82
  1. The script is called as soon as the browser interpreter gets to line 20.

  2. index is the position of the current div, currentClass get the value of that div's class attribute (zero, or more space separated classes).

  3. What is returned is added to the current class(es) of that div.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.