With jQuery, you can get to just about anything on a web page. In this entry, I’ll show you a few ways you can use jQuery’s versatile selector expressions to traverse to an element — or group of elements — in the DOM.
I’ve put together a short paragraph and an ordered list scattered with inline elements such as <em>, <code>, and links. It’s all wrapped in a DIV with an ID of “jqdt,” which allows me to focus the demonstration to one area of this page.
Each button below the “jqdt” DIV will toggle a yellow background on and off for the parts of the DIV described.
$('li:eq(0)')gets the first list item
$('li:lt(3)')gets the first 3 list items. “lt” stands for “less than,” and it starts counting at 0, not 1.
$('li:not(.goofy)')gets list items 1, 3, and 4, because they’re not “goofy.”
$('p a[href*="#"]')gets any links that are inside a paragraph and have an “href” attribute
starting with “#” — in other words, same-page links. Note the space between the “p” and the “a”; that means that the “a” is a descendant of the “p.”
$('code, li.goofy')gets all code elements and any list item with a class of “goofy.”
$('ol .goofy > strong')gets all strong elements that are children of any element with a class of “goofy” as long as the class somewhere inside (i.e. a descendent) of an ordered list. Notice that the word “item” is not highlighted because, even though it’s inside “.goofy,” it’s not a direct child. Only “goofy” is a direct child of “.goofy.” Maybe we should call it “goofy jr.”
$('li + li > a[href$=pdf]')gets all links ending in “pdf” that are children of any list item that has another list item as its previous sibling. It won’t get the first list item’s silly.pdf because that list item has no other list items before it.
$('span:hidden')gets any span element that is hidden.
Note: The selectors used for the toggle buttons are identical to the ones shown next to each button, except that they are preceded by
$('#jqdt').find to target the highlighting.
jQuery’s selector expressions cover the full range of CSS 1-3, along with basic XPath and a few jQuery-only expressions. For a complete list, visit jquery.com
Next time, I’ll explore jQuery functions such as
siblings() that complement the above selector expressions to give you full DOM-traversing power!