Dynamically Add / Remove CSS Class with jQuery

0 Flares Twitter 0 Facebook 0 Google+ 0 Pin It Share 0 LinkedIn 0 Filament.io 0 Flares ×

jQuery JavaScript FrameworkjQuery has built in functions designed to add and remove a CSS class or multiple CSS classes from selected elements (selectors).

.addClass() – Adds the specified class(es) to each of the set of matched elements.
The function simply adds the class, appending it to any which may already be assigned to the elements.

$("p").addClass('newClass');

More than one class may be added at a time to the set of matched elements. Each parameter must separated by a space.

$("p").addClass("newClass1 newClass2");

It is important to note that these classes will not replace existing classes. If you wish to replace the existing style you can first use the .removeClass() function or use the .attr(“class”,”newClass”) function instead.

.removeClass() – Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
If no class names are specified in the parameter, all classes will be removed.

$("p").removeClass();

If a class name is included as a parameter, then only that class will be removed from the set of matched elements.

$("p").removeClass("newClass");

Both these functions can be used together in the same line as well.

$("p").removeClass("newClass1 newClass2").addClass("newClass3");

This resulting code would remove newClass1 and newClass2 as well as add newClass3.

These functions can be used with any selected element where style is valid.

Speak Your Mind

*

0 Flares Twitter 0 Facebook 0 Google+ 0 Pin It Share 0 LinkedIn 0 Filament.io 0 Flares ×