Pages

2 Sept 2013

Manipulating and Accessing CSS Class Names in Jquery

jQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this: 

$("div").addClass("content"); // adds class "content" to all <div> elements
$("div").removeClass("content"); // removes class "content" from all <div> elements
$("div").toggleClass("content");

// toggles the class "content" on all <div> elements (adds it if it doesn't exist, //
and removes it if it does)

You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an if statement. Here is an example: 

if ($("#myElement").hasClass("content")) {
 // do something here
}

You could also check a set of elements (instead of just one), and the result would return "true" if any one of the elements contained the class.

No comments:

Post a Comment