Adding and removing class names using jQuery

Leave a Comment

Adding class names to all the elements of a matched set is an easy operation with addClass() method.

Removing class names is just as straightforward with removeClass() method.

jQuery makes this easy with the toggleClass() method.

One situation where the toggleClass() method is most useful is when we want to switch visual renditions between elements quickly and easily.
function swapThem() {
  $('tr').toggleClass('striped');
}

Above function uses the toggleClass() method to toggle the class named striped for all <tr> elements.
$(function(){/
  $("table tr:nth-child(even)").addClass("striped");
  $("table").mouseover(swapThem).mouseout(swapThem);
});

The first statement in the body of this handler applies the class striped to every other row of the table using the nth-child selector.

The second statement establishes event handlers for mouseover and mouseout events that both call the same swapThem function.

0 comments:

Post a Comment