Java Reference
In-Depth Information
jQuery also lets you use multiple selectors in one function call. Simply delimit each selector with a
comma as shown in the following code:
$("a, #myDiv, .myCssClass, p > span")
This code retrieves all
<a/>
elements, an element with an
id
of
myDiv
, elements with the CSS class
myCssClass
, and all
<span/>
children of
<p/>
elements. If you wanted to change the text's color of
these elements to red, you could simply use the following code:
$("a, #myDiv, .myCssClass, p > span").attr("style", "color:red;");
This isn't the best way to change an element's style. In fact, jQuery provides you with many methods
to alter an element's style.
Note
For a complete list of supported selectors, se
e
http://docs.jquery
.com/Selectors
.
Changing style
Changing an element's style requires you to either modify individual CSS properties or manipulate
its CSS classes. jQuery makes it easy to do both. To change individual CSS properties, the
jQuery
object has a method called
css()
, and you can use this method in two ways.
First, you can pass two arguments to the
css()
method: the CSS property's name and its value. For
example:
$("#myDiv").css("color", "red");
This code sets the
color
property to red, thus changing the element's text color to 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 want to change an element's background color, you can pass
background‐color
or
backgroundColor
to the method, like this:
var allParagraphs = $("p");
allParagraphs.css("background-color", "yellow"); // correct!
allParagraphs.css("backgroundColor", "blue"); // correct, too!
This code changes the background color of every
<p/>
element in the page to yellow and then to
blue.
Note
It's important to remember that jQuery's methods work with one or
multiple elements. It doesn't matter how many elements are referenced by a
jQuery
object, a method like
css()
will change the style of every element in
the object.