Java Reference
In-Depth Information
Changing Style
As with the DOM, you change an element's style by changing individual CSS properties or by changing
an element's CSS class. To do so, you use the css() method. This method can accept two arguments: the
property's name and its value.
$(“#myDiv”).css(“color”, “red”);
This code sets the color property to red, thus making the text's color red. The property names you pass
to the css() method can be in either style sheet format or in script format. That means if you wanted to
change an element's background color, you can pass background-color or backgroundColor to the
method, like this:
$(“#myDiv”).css(“background-color”, “yellow”); // CORRECT!!!
$(“#myDiv”).css(“backgroundColor”, “yellow”); // CORRECT, TOO!!!
Typically, though, if you want to change an element's style (that isn't animation-based), it's better to
change the element's CSS class instead of the individual style properties. Doing so keeps the style con-
tent in the style sheet where it belongs.
Using Multiple CSS classes
The jQuery object exposes several methods to manipulate an element's className property. Before
looking at them, you should know that it's legal for an element to have multiple CSS classes. Look at the
following HTML:
<div class=”myClass1 myClass2”>
My div with two CSS classes!
</div>
To apply two or more CSS classes to an element, simply separate the class names with spaces. In
this HTML snippet, the style of two CSS classes are applied to the <div/> element: myClass1 and
myClass2. This concept is being introduced to you because jQuery's methods to manipulate class
names are built around this concept.
The fi rst method, addClass(), adds the specifi ed CSS class(es) to the element.
$(“#myDiv”).addClass(“myClass1”)
.addClass(“myClass2”);
This code adds the myClass1 and myClass2 CSS classes to the element. You can shorten this code by
simply passing both class names to the addClass() method in one call:
$(“#myDiv”).addClass(“myClass1 myClass2”);
Just make sure you separate the class names with a space. When you want to remove a specifi c class or
classes from the element, use the removeClass() method.
$(“#myDiv”).removeClass(“myClass2”);
Search WWH ::




Custom Search