Java Reference
In-Depth Information
Many times, however, you need to change more than one CSS property. Although you can easily
accomplish this by calling
css()
multiple times like this:
// don't do this
allParagraphs.css("color", "blue");
allParagraphs.css("background-color", "yellow");
a better solution would be to pass an object that contains the CSS properties and their values to the
css()
method. The following code calls
css()
once and achieves the same results:
allParagraphs.css({
color: "blue",
backgroundColor: "yellow"
});
Here, you pass an object that has
color
and
backgroundColor
properties to the
css()
method, and
jQuery changes the element's or elements' text color to blue and background color to yellow.
Typically, though, if you want to change an element's style, it's better to change the element's CSS
class instead of individual style properties.
adding and removing CSS Classes
The
jQuery
object exposes several methods to manipulate an element's
className
property; you
can add, remove, and even toggle the classes that are applied to an element.
Note
Did you know you can assign multiple CSS classes to an element?
Simply separate each class name with a space!
Let's assume that the following HTML is in one of your web pages:
<div id="content" class="class-one class-two">
My div with two CSS classes!
</div>
This HTML defines a
<div/>
element with two CSS classes,
class‐one
and
class‐two
. You need to
apply two more classes (
class‐three
and
class‐four
) to this element, and jQuery makes that very
easy to do with the
addClass()
method. For example:
var content = $("#content");
content.addClass("class-three");
content.addClass("class-four");
This code first retrieves the
<div/>
element and then calls the
addClass()
method to add the desired
classes. But you can simplify this code by using a technique called
method chaining
. Most jQuery
methods return a
jQuery
object, so it's possible to call a method immediately after calling another
method—essentially chaining the method calls as demonstrated with this code:
content.addClass("class-three").addClass("class-four");