← Back to jQuery Course | Chapter 2: Selectors | Lesson 4 of 10

Hierarchy Selectors

A space selects descendants at any level.

Descendant Selector

Writing two selectors separated by a space finds every element nested anywhere inside the first, regardless of how many levels deep it sits. Because it searches at any depth, this is the least specific and potentially slowest of the hierarchy selectors on a large page.

Example: Descendant Selector

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div><ul><li>Item</li></ul></div>
    <script>
      console.log($("div li").length);
    </script>
  </body>
</html>

Child Selector

A greater-than sign between two selectors, like 'ul > li', restricts the match to direct children only, ignoring any elements nested more deeply inside grandchildren or further down.

Example: Child Selector

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <ul><li>A<ul><li>Nested</li></ul></li></ul>
    <script>
      console.log($("ul > li").length);
    </script>
  </body>
</html>

Adjacent Sibling

A plus sign between two selectors, like 'h2 + p', matches only the single element that comes immediately after the first as a sibling, skipping anything further down the sibling list.

Example: Adjacent Sibling

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <h2>Heading</h2><p>First</p><p>Second</p>
    <script>
      console.log($("h2 + p").text());
    </script>
  </body>
</html>

General Sibling

A tilde between two selectors, like 'h2 ~ p', matches every later sibling with the same parent, not just the very next one -- broader than the plus-sign adjacent-sibling selector. This is useful when several sibling elements need the same treatment after a specific marker element, regardless of exact position.

Example: General Sibling

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <h2>Heading</h2><p>First</p><p>Second</p>
    <script>
      console.log($("h2 ~ p").length);
    </script>
  </body>
</html>

Combine Hierarchy

Combining hierarchy selectors, such as 'div > ul li.active', lets you build precise, multi-level queries that pinpoint exactly the elements you need without over- or under-selecting.

Example: Combine Hierarchy

javascript
<!DOCTYPE html>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  </head>
  <body>
    <div><ul><li>Off</li><li class="active">On</li></ul></div>
    <script>
      console.log($("div > ul li.active").text());
    </script>
  </body>
</html>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.