Saturday, July 9, 2011

Manipulating and Accessing CSS Class Names & CSS Style

Manipulating and Accessing CSS Class Names :
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
elements
$("div").removeClass("content"); // removes class "content" from all
elements
$("div").toggleClass("content");// toggles the class "content" on all
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.

Manipulating CSS Styles with jQuery:
CSS styles can be added to elements easily using jQuery, and it's done in a cross-browser fashion. Here are some
examples to demonstrate this:
$("p").css("width", "400px"); // adds a width to all paragraphs
$("#myElement").css("color", "blue") // makes text color blue on element #myElement
$("ul").css("border", "solid 1px #ccc") // adds a border to all lists

No comments:

Post a Comment