Java Reference
In-Depth Information
Even though you know only one element can be selected with this code, you can still use the length
property to make sure the element was found in the page. If the element wasn't found, length will be 0.
You can apply the same logic to select elements by their CSS class name. Simply pass the CSS selector to
the jQuery function like this:
$(“.myCssClass”)
Because jQuery uses CSS selectors to select elements, you can easily select elements based on their hier-
archy. Consider the following HTML:
<p>
<div>Div 1</div>
<div>Div 2</div>
<span>Span 1</div>
</p>
<span>Span 2</span>
This HTML code defi nes a <p/> element that contains two <div/> elements and a <span/> element.
Outside the <p/> element is another <span/> element. You would have to write several lines of code to
identify and retrieve the <span/> element inside the <p/> element if you use traditional DOM methods
and properties. With jQuery, you only need to write one:
$(“p > span”)
This line of code uses the parent > child CSS selector syntax to select all <span/> elements that are
children to <p/> elements.
Internet Explorer 6 does not natively support this specifi c CSS selector; however, you would fi nd it still
works if you ran this code in that browser. JQuery and other frameworks support a wide array of CSS
selectors — even if the selector is not supported by the browser. See the framework's web site for a com-
plete list of supported CSS selectors.
The jQuery function also grants you the ability to use multiple selectors in one function call. Look at the
following code as an example:
$(“a, #myDiv, .myCssClass, p > span”)
Simply delimit each selector with a comma. 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 set the text 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.
For a complete list of supported selectors, see http://docs.jquery.com/Selectors .
Search WWH ::




Custom Search