Scrivito is proudly made by JustRelate Group in Berlin, Germany, and Wrocław, Poland.
Scrivito is proudly made by JustRelate Group

DOM Traversing with jQuery - What You Need to Know

The Document Object Model (DOM) is an object-oriented representation of a web page which can be modified with a scripting language, like JavaScript: we can think of the DOM as a representation of an HTML page in a way JavaScript can understand. JQuery is a very popular JavaScript library that simplifies the use of JavaScript features like event handlers, animations or AJAX requests, and it really shines when we need to traverse and manipulate the DOM.

Why jQuery and not just JavaScript?

Before risking to step into a dangerous misunderstanding, let’s make one important thing clear: jQuery is JavaScript and you can write code mixing both syntaxes (provided that the jQuery library is loaded). Actually it is a library that simplifies the syntax needed to write some JavaScript functions, especially when it comes to DOM traversing: that’s why this library has grown so popular among frontend developers, particularly among those who don’t have a traditional programming background.

Let’s start

jQuery provides many traversing methods; one of the most useful and easiest to demonstrate is .children(). It returns all the children of a given element (or DOM node). Considering the following HTML code:

<p class='inputText'>
  This is a <i>demo</i> text that contains several <b>bolds</b> and <i>italics</i> with the only purpose of demonstrating <strong>how</strong> the<i> jQuery</i> <b>.children()</b> method works.
<h2 class='outputLabel'>We have </h2>

This tiny jQuery call selects all the children of the p element (all the <b> and <i> tags) and highlights them in yellow: we now have our filtered collection as a variable and we can subsequently use it for other purposes (highlighted in green):

var $children = $('p.inputText').children(),
    $childrenSize = $children.length;

$children.css('background-color', 'yellow');
$('<span>' +$childrenSize+ ' elements:'+'</span>').appendTo('.outputLabel');
$($children).clone().insertAfter('.outputLabel').css('background-color', 'lime');

The way jQuery handles DOM traversing is very simple and closely resembles CSS; with just one line of code $('p.inputText').children() we have accomplished the task to isolate the needed elements. The .children() method accepts one or more selectors as an argument, so var $children = $('p.inputText').children('i') selects only the italics but not the bolds, while var $children = $('p.inputText').children('i, b') selects everything but the single <strong> tag. 

Other methods

jQuery features many traversing methods, and its array of possibilities is wide enough to allow us to easily manipulate the DOM in every way we need. Good knowledge of CSS is clearly beneficial. Let’s get an overview of these methods.

  • .parent() and parents()

    Both methods return the ancestors of the selected element, and the resulting collection can be filtered by a selector (as we have seen with .children()). The first method lets you traverse the DOM by just one level, thus getting the immediate ancestor, while the second traverses the DOM up to the document’s root.

  • .find()

    This method selects all the descendants of a supplied selector. Unlike most of the tree traversal methods, a matching selector is required. If we need to retrieve all of the descendants, we can pass in the universal selector * to accomplish this.

  • .siblings()

    This method selects all the siblings of a given element, optionally filtered by a selector. In the following example, only the <li> of the first list will be highlighted (a and c); if I had not supplied the li selector, the second ul would have been included as well.

  <li class="selected">b</li>
$('.selected').siblings('li').css('background-color', 'salmon');
  • .closest()

    This method is very similar to .parents() but with some differences:

    a) It doesn’t traverse the DOM up to the root but stops when it finds the supplied matching selector.

    b) It begins searching at the current element, while .parents() starts at the parent element.

    c) Elements in the resulting jQuery object are sorted in document order while .parents() returns them in reverse order. 

  • .next() and .nextAll()

    These methods are pretty intuitive since they select the sibling(s) following the given item; with .nextAll(), all the items following the given one are selected. Considering the HTML code of the above example, $('.selected').nextAll().css('background-color', 'salmon') highlights everything that follows item b (excluded), including the second-level list. On the other hand, $('.selected').next().css('background-color', 'lime') highlights item c only.

  • .prev() and prevAll()

    This is something every web designer has always dreamed of having in CSS: a means of selecting a preceding sibling of an element. As you probably have guessed, .prevAll() selects all the ancestors, and both methods accept a selector as a filter.

  • .nextUntil(), .prevUntil() and .parentsUntil()

    These methods work like .nextAll(), .prevAll() and parents() but don’t include the matched element.

Traversing can be much more

The concept of traversing can be extended beyond the idea of moving up and down the DOM, up to including the numerous filtering possibilities that jQuery puts at our disposal. It is surely an interesting topic and there would be much to say but we think that, for now, it is better to keep the two topics separated; mixing traversing and filtering up may lead to confusion and these basic but essential topics have to be carefully assimilated to build up a solid jQuery foundation. 

Ready to start? Create your free account now