jQuery addClass(), removeClass(), toggleClass() example

.addClass() jQuery method will be used to add one or more css class to the selected elements.

Syntax:

  1. $(selector).addClass("className")
  2. $(selector).addClass(function(index,currentClassName){})

Example

$("div").addClass("greenbackground");
In the above example css class "greenbackground" will be added to all the div elements

$("div").addClass("greenbackground green");
In the above example both the css classes "greenbackground" and "green" will be added to all the div elements

$("div").addClass(function (index, currentclassname) { if (currentclassname == "green") return "greenbackground" else return ""; });
In the above example css class "greenbackground" will be added to the div elements which are having the css class "green".

.removeClass() jQuery method will be used to remove one or more css class to the selected elements.

Syntax:

  1. $(selector).removeClass("className")
  2. $(selector).removeClass(function(index,currentClassName){})

Example

$("div").removeClass("greenbackground");
In the above example css class "greenbackground" will be removed from all the div elements

$("div").removeClass("greenbackground green");
In the above example both the css classes "greenbackground" and "green" will be removed from all the div elements

$("div").removeClass(function (index, currentclassname) { if (currentclassname.indexOf("divbold") > -1) return "greenbackground" else return ""; });
In the above example css class "greenbackground" will be removed from the div elements which are having the css class "divbold".

.toggleClass() jQuery method will be used to toggle (removes if class already exist, else add the class) the class from the selected elements.

Syntax :

  1. $(selector).toggleClass("className")
  2. $(selector).toggleClass("className",addOrRemove) ->addOrRemove is boolean value( true/false)

Example

$("div").toggleClass("greenbackground");
In the above example css class "greenbackground" will be removed from the each div elements if it already have the css class, other wise it will add the css class to the element.

$("div").toggleClass("greenbackground green");
In the above example the css classes "greenbackground" and "green" will be removed from the each div elements if it already have the css class, other wise it will add the css class to the element.