Retrieving elements by their hierarchy

Retrieving a set of elements by their class name is a nice feature, but often you don’t want to search the whole page. Sometimes you may want to select only the direct children of a certain element. Consider the following HTML fragment from the sample DOM in the Selectors Lab:

<ul class="my-list">
  <li>
    <a href="http://jquery.com">jQuery supports</a>
    <ul>
      <li><a href="css1">CSS1</a></li>
      <li><a href="css2">CSS2</a></li>
      <li><a href="css3">CSS3</a></li>
      <li>Basic XPath</li>
    </ul>
  </li>
  <li>jQuery also supports
    <ul>
      <li>Custom selectors</li>
      <li>Form selectors</li>
    </ul>
  </li>
</ul>

Suppose that you wanted to select the a element pointing to the jQuery website but not those to various local pages describing the different CSS specifications. To achieve this goal you can use the Child selector, in which a parent and its direct child are separated by the right angle bracket character (>). You can write

ul.my-list > li > a

This selector will collect only links that are direct children of list elements, which are in turn direct children of the <ul> that have class my-list. The links contained in the sublists are excluded because the ul element serving as their parent doesn’t have the class my-list. Running this selector in the lab page gives the result shown in figure 2.3.

Figure 2.3. With the selector ul.my-list > li > a, only the direct children of parent nodes are matched.

The Child selector isn’t the only one available to express a relation between two or more elements based on the DOM tree’s hierarchy. Table 2.2 provides an overview of the selectors of this type.

Table 2.2. The CSS hierarchy selectors supported by jQuery
SelectorDescriptionIn CSS?
E FMatches all elements with tag name F that are descendants of E
E>FMatches all elements with tag name F that are direct children of E
E+FMatches all elements with tag name F that are immediately preceded by sibling E
E~FMatches all elements with tag name F preceded by any sibling E

All the selectors described in the table but the first one are part of the CSS2.1 specifications, so they aren’t supported by Internet Explorer 6. But you can use all of them safely in jQuery because the library deals with these kinds of problems for you.

These selectors improved your ability to precisely target the DOM nodes you want to act upon. Over time a lot of other CSS selectors have been created to place more power in your hands. One of the features introduced was the ability to select elements based on their attributes. These selectors are the topic of the next section.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *