blog

  • Home
  • blog
  • A Comprehensive Look at jQuery DOM Traversal

A Comprehensive Look at jQuery DOM Traversal

Separate elements of code in hospital drips. A metaphor for DOM traversal.

[special]DOM traversal means that once you have selected an element or elements on a web page, you can move through the page elements relative to your initial selection. During this process, you can either replace the original selection with a new one or add and subtract elements from it.[/special]

In this article we will look at the available methods for jQuery DOM traversal, and see how the library provides many ways for us to easily select elements based on their relationships to other elements in the page.

Filtering Elements

Let’s begin by looking at how to filter a selection down to something more specific. You can filter elements based on a lot of conditions like their position with respect to other elements and whether or not they have a specific class. Most of the time, you will end up with fewer elements selected than you began with.

Here is a list of the different filtering methods:

  • eq — This method reduces the set of matched elements to the one that is located at the index you specified. The indexing is zero based. Therefore, to select the first element, you will have to use $("selector").eq(0). Starting with version 1.4, you can provide a negative integer to begin counting elements from the end instead of the beginning.

  • first and last— The first method will return just the first element from the set of matched elements while last will return the last element from the set of matched elements. Neither of these methods accepts any arguments.

  • slice — If you are looking for all elements in a set whose index lies within a given range, you can using slice(). This method accepts two arguments. The first one specifies the starting index from which the method should start slicing and the second argument specifies the index at which the selection should end. The second argument is optional and if omitted results in the selection of all elements whose index is greater than or equal to start.

    See the Pen eq and slice methods by SitePoint (@SitePoint) on CodePen.

  • filter — This method will reduce your set of elements to those that either match the selector or pass the criteria set by you in the function that is passed to this method. Here is one example of this method with selectors:

    $("li").filter(":even").css( "font-weight", "bold" );
    

    You could also select the same elements using a function:

    $("li")
    .filter(function( index ) {
       return index % 2 === 0;
    })
    .css( "font-weight", "bold" );
    

    You can also use the function to perform more complicated selections like:

Continue reading %A Comprehensive Look at jQuery DOM Traversal%

LEAVE A REPLY