Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@aaronsummers
Last active April 6, 2022 07:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save aaronsummers/a403b94d4fa4291b827541fafad76a66 to your computer and use it in GitHub Desktop.
Save aaronsummers/a403b94d4fa4291b827541fafad76a66 to your computer and use it in GitHub Desktop.
Traversing the DOM with jQuery

Navigating a page with jQuery

jQuery is a lightweight, "write less, do more", JavaScript library.

The purpose of jQuery is to make it much easier to use JavaScript on your website.

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

The jQuery library contains the following features:

  • HTML/DOM manipulation
  • CSS manipulation
  • HTML event methods
  • Effects and animations
  • AJAX
  • Utilities

First lets see how we can select items within the DOM

You can select elements in the DOM in exactly the same way as you can in your CSS by using tag, #id, .class, [attribute=""] and :pseudo selectors. Below are some examples.

  • tag
    $('div');
  • class name:
    $('.class-name');
  • ID:
    $('#id');
  • attribute:
    $('input[type="checkbox"]');
  • pseudo selectors
    $('.class-name:nth-of-type(3)');
    $('.class-name:first-child()');
    $('.class-name:last-child()');

jQuery also makes available some unique selectors that are only available within jQuery, this is called filtering, more on this below in traversing the DOM. But bare in mind that CSS selectors will always be quicker than jQuery selctors.

  • To select the first element
    $('.class-name').first();
  • To select the last element
    $('.class-name').last();
  • To select the nth element, where N = number ( starting from 0 )
    $('.class-name').eq(N);

Now we can select elements, let's see how to navigate the DOM

Navigating the DOM is probably the most important thing to learn from a front-end development point of view. It's not always possible to directly select the element that you're trying to manipulate.

jQuery provides a variety of methods that allow us to traverse the DOM.

The largest category of traversal methods are tree-traversal.


jQuery Traversing - Ancestors

With jQuery you can traverse up the DOM tree to find ancestors of an element.

An ancestor is a parent, grandparent, great-grandparent, and so on

Traversing Up the DOM Tree

Three useful jQuery methods for traversing up the DOM tree are:

    .parent()
    .parents()
    .parentsUntil()
jQuery parent() Method

The .parent() method returns the direct parent element of the selected element.

This method only traverse a single level up the DOM tree.

The following example returns the direct parent element of each elements:

    $(document).ready(function(){
      $("span").parent();
    }); 

example:

  <div class="ancestors">
    <div>div (great-grandparent)
      <ul>ul (grandparent)  
        <li>li (direct parent) [selected]
          <span>span</span>
        </li>
      </ul>   
    </div>   
  </div>
jQuery parents() Method

The .parents() method returns all ancestor elements of the selected element, all the way up to the document's root element (<html>).

The following example returns all ancestors of all <span> elements:

    $(document).ready(function(){
      $("span").parents();
    }); 

example:

every element that wraps the span will be selected

  <body class="ancestors">body (great-great-grandparent) [selected]
    <div>div (great-grandparent) [selected]
      <ul>ul (grandparent) [selected) ]
        <li>li (direct parent) [selected]
          <span>span</span>
        </li>
      </ul>   
    </div>
  </body>

You can also use an optional parameter to filter the search for ancestors.

The following example returns all ancestors of all <span> elements that are <ul> elements:

  $(document).ready(function(){
    $("span").parents("ul");
  }); 

example:

  <body class="ancestors">body (great-great-grandparent)
    <div>div (great-grandparent)
      <ul>ul (grandparent) [selected) ]
        <li>li (direct parent)
          <span>span</span>
        </li>
      </ul>   
    </div>
  </body>
jQuery parentsUntil() Method

The .parentsUntil() method returns all ancestor elements between two given arguments.

The following example returns all ancestor elements between a <span> and a <div> element:

    $(document).ready(function(){
      $("span").parentsUntil("div");
    }); 

example:

  <body class="ancestors"> body (great-great-grandparent)
    <div>div (great-grandparent)
      <ul>ul (grandparent) [selected]
        <li>li (direct parent) [selected]
          <span>span</span>
        </li>
      </ul>   
    </div>
  </body>

jQuery Traversing - Descendants

With jQuery you can traverse down the DOM tree to find descendants of an element.

A descendant is a child, grandchild, great-grandchild, and so on.

Traversing Down the DOM Tree

Two useful jQuery methods for traversing down the DOM tree are:

    .children()
    .find()
jQuery .children() Method

The .children() method returns all direct children of the selected element.

This method only traverses a single level down the DOM tree. The following example returns all elements that are direct children of each <div> elements:

    $(document).ready(function(){
      $("div").children();
    }); 

example:

  <div class="descendants">div (current element) 
    <p>p (child) [selected]
      <span>span (grandchild)</span>   
    </p>
    <p>p (child) [selected]
      <span>span (grandchild)</span>
    </p> 
  </div>

The following example returns all

elements with the class name "first", that are direct children of <div>:

You can also use an optional parameter to filter the search for children.

The following example returns all

elements with the class name "first", that are direct children of

:

    $(document).ready(function(){
      $("div").children("p.first");
    }); 

example:

  <div class="descendants" style="width:500px;">div (current element) 
    <p class="first">p (child) [selected]
      <span>span (grandchild)</span>   
    </p>
    <p class="second">p (child)
      <span>span (grandchild)</span>
    </p> 
  </div>
jQuery find() Method

The .find() method returns descendant elements of the selected element, all the way down to the last descendant.

    $(document).ready(function(){
      $("div").find("span");
    }); 

example:

  <div class="descendants" style="width:500px;">div (current element) 
    <p>p (child)
      <span>span (grandchild)</span> [selected) ]
    </p>
    <p>p (child)
      <span>span (grandchild)</span> [selected]
    </p> 
  </div>

jQuery Traversing - Siblings

With jQuery you can traverse sideways in the DOM tree to find siblings of an element.

Siblings share the same parent. Traversing Sideways in The DOM Tree

There are many useful jQuery methods for traversing sideways in the DOM tree:

  • .siblings()
  • .next()
  • .nextAll()
  • .nextUntil()
  • .prev()
  • .prevAll()
  • .prevUntil()

jQuery .siblings() Method

The .siblings() method returns all sibling elements of the selected element.

The following example returns all sibling elements of <h2>:

    $(document).ready(function(){
      $("h2").siblings();
    }); 

example:

    <body class="siblings">

        <div>div (parent)
            <p>p</p> [selected]
            <span>span</span> [selected]
            <h2>h2</h2>
            <h3>h3</h3> [selected]
            <p>p</p> [selected]
        </div>

    </body>

You can also use an optional parameter to filter the search for siblings.

The following example returns all sibling elements of <h2> that are <p> elements:

    $(document).ready(function(){
      $("h2").siblings("p");
    }); 

example:

    <body class="siblings">

        <div>div (parent)
            <p>p</p> [selected]
            <span>span</span>
            <h2>h2</h2>
            <h3>h3</h3>
            <p>p</p> [selected]
        </div>

    </body>

jQuery .next() Method

The .next() method returns the next sibling element of the selected element.

The following example returns the next sibling of <h2>:

    $(document).ready(function(){
      $("h2").next();
    }); 

example:

    <body class="siblings">

        <div>div (parent)
            <p>p</p>
            <span>span</span>
            <h2>h2</h2>
            <h3>h3</h3> [selected]
            <p>p</p>
        </div>

    </body>

jQuery .nextAll() Method

The .nextAll() method returns all next sibling elements of the selected element.

The following example returns all next sibling elements of <h2>:

    $(document).ready(function(){
      $("h2").nextAll();
    }); 

example:

    <body class="siblings">

        <div>div (parent)
            <p>p</p>
            <span>span</span>
            <h2>h2</h2>
            <h3>h3</h3> [selected]
            <h4>h4</h4> [selected]
            <h5>h5</h5> [selected]
            <h6>h6</h6> [selected]
            <p>p</p> [selected]
        </div>

    </body>

jQuery nextUntil() Method

The nextUntil() method returns all next sibling elements between two given arguments.

The following example returns all sibling elements between a <h2> and a <h6> element:

    $(document).ready(function(){
      $("h2").nextUntil("h6");
    }); 

example:

    <body class="siblings">

    <div>div (parent)
        <p>p</p>
        <span>span</span>
        <h2>h2</h2>
        <h3>h3</h3> [selected]
        <h4>h4</h4> [selected]
        <h5>h5</h5> [selected]
        <h6>h6</h6>
        <p>p</p>
    </div>

    </body>

jQuery .prev(), .prevAll() & .prevUntil() Methods

The .prev(), .prevAll() and .prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).

jQuery Traversing - Filtering

The .first(), .last(), .eq(), .filter() and not() Methods

The most basic filtering methods are .first(), .last() and .eq(), which allow you to select a specific element based on its position in a group of elements.

Other filtering methods, like .filter() and .not() allow you to select elements that match, or do not match, a certain criteria.

jQuery first() Method

The .first() method returns the first element of the specified elements.

jQuery .last() Method

The .last() method returns the last element of the specified elements.

jQuery .eq() method

The .eq() method returns an element with a specific index number of the selected elements.

The index numbers start at 0, so the first element will have the index number 0 and not 1.

jQuery .filter() Method

The .filter() method lets you specify a criteria. Elements that do not match the criteria are removed from the selection, and those that match will be returned.

The following example returns all <p> elements with class name "intro":

    $(document).ready(function(){
      $("p").filter(".intro");
    }); 

example:

    <h1>Welcome to My Homepage</h1>

    <p>My name is Donald.</p>
    <p class="intro">I live in Duckburg.</p> [selected]
    <p class="intro">I love Duckburg.</p> [selected]
    <p>My best friend is Mickey.</p>

jQuery .not() Method

The .not() method returns all elements that do not match the criteria.

Tip: The .not() method is the opposite of .filter().

The following example returns all <p> elements that do not have class name "intro":

    $(document).ready(function(){
      $("p").not(".intro");
    }); 

example:

    <h1>Welcome to My Homepage</h1>

    <p>My name is Donald.</p>
    <p class="intro">I live in Duckburg.</p>
    <p>I love Duckburg.</p> [selected]
    <p>My best friend is Mickey.</p>

For a full list of traversing methods please see the jQuery documentation Traversing


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment