• 20 hours
  • Easy

Free online content available in this course.


Got it!

Last updated on 8/5/19

Traverse the DOM

Log in or subscribe for free to enjoy all this course has to offer!

In this chapter, you'll see how to use JavaScript to traverse the DOM.

Sample page

It's time to switch files! Add this code to your course.html file or follow along in the CodePen link further below: 

<!doctype html>

    <meta charset="utf-8">
    <title>Seven wonders of the world</title>

    <h1>Seven wonders of the world</h1>
    <p>Do you know the seven wonders of the world?</p>
    <div id="content">
        <h2>Wonders from Antiquity</h2>
        <p>This list comes to us from ancient times.</p>
        <ul class="wonders" id="ancient">
            <li class="exists">Great Pyramid of Giza</li>
            <li>Hanging Gardens of Babylon</li>
            <li>Lighthouse of Alexandria</li>
            <li>Statue of Zeus at Olympia</li>
            <li>Temple of Artemis at Ephesus</li>
            <li>Mausoleum at Halicarnassus</li>
            <li>Colossus of Rhodes</li>
        <h2>Modern wonders of the world</h2>
        <p>This list was decided by vote.</p>
        <ul class="wonders" id="new">
            <li class="exists">Petra</li>
            <li class="exists">Great Wall of China</li>
            <Li class="exists">Christ the Redeemer</Li>
            <Li class="exists">Machu Picchu</Li>
            <li class="exists">Chichen Itza</li>
            <li class="exists">Colosseum</li>
            <li class="exists">Taj Mahal</li>

    <script src="../js/course.js"></script>


Select items

The DOM node by node

In the previous chapter, we saw how to navigate the DOM node structure of a web page beginning with the root node and using the  childNodes  property to move down levels in the structure of the page.

Suppose we want to select the title "Seven wonders of the world" of our web page. All DOM elements have a method called getElementsByTagName. This returns a list of items that have the name of the tag that's passed as a parameter.

The search happens through all the sub-elements of the node on which the method is called, not only through its direct children.

With this method, selecting the first  h2  is easy!

// Get first header
var titleElements = document.getElementsByTagName("h2"); // All h2s
console.log(titleElements[0]); // Show the first h2

Selecting items according to class

DOM elements also feature a method called getElementsByClassName. It returns a list of elements with the class name as a parameter. Again, the search covers all sub-elements of the node on which the method is called.

To select and display all document elements with the class "wonders" you can write the following code:

// Get all elements that have the class "wonders"
var wondersElements = document.getElementsByClassName("wonders");
for (var i = 0; i < wondersElements.length; i++) {

Remember, you can test out these examples on CodePen by uncommenting the relevant lines of code, for example:

Uncomment the lines of JS you want to test
Uncomment the lines of JS you want to test

Selecting an item by its ID

Lastly, each element of the DOM provides a method called getElementById that returns among all sub-elements with the id passed as a parameter.

The following code selects and displays the list with ID "new."

// Get element with the ID "new"

Selecting elements via CSS selectors

You can also use CSS selectors to select elements that you'll then modify with JavaScript.

For example, let's say that you want to grab all the <li>s of wonders that are both "ancient" and "still exist."

// All "ancient" wonders that still exist
console.log(document.getElementById("ancient").getElementsByClassName("exists").length); // Will show 1

This syntax is a little clunky though.

Let's learn two new methods that make finding elements easier. The first is querySelectorAll, with which you can use CSS selectors to identify elements. In CSS, you identify element types, classes, etc., to which you apply style rules, ex:

h1 {
    color: red;

You can use those same selectors in JavaScript!

// All paragraphs
console.log(document.querySelectorAll("p").length); // Will be 3

// All paragraphs inside the "content" ID block
console.log(document.querySelectorAll("#content p").length); // Will be 2

// All elements with the "exists" class
console.log(document.querySelectorAll(".exists").length); // Will be 8

// All "ancient" wonders that still exist
console.log(document.querySelectorAll("#ancient > .exists").length); // Will be 1

The second method to use with CSS selectors is called querySelector. It works the same way as querySelectorAll but only returns the first matching element.

// The first paragraph

Choosing a selection method

We have studied several ways of selecting DOM elements. How do you choose the right one?

You could always use querySelectorAll and querySelector, but they don't perform as well asgetElementsByTagNamegetElementsByClassName and getElementById.

Here's are some general rules of thumb.

Number of items to get

Selection criteria



By tag



By class



Not by class or tag





Only one (the first)

Not ID


Get element information

The DOM also provides information on the items you've just selected.

HTML content

The innerHTML property will retrieve the HTML contents of your DOM element.

// The HTML content of the "content" ID

Textual content

The textContent property returns all the text content of a DOM element, without any HTML markup.

// The href attribute of the first link


The getAttribute method can be applied to a DOM element and will return the value of the attribute.

// ID of the first list

// href attribute of the first link

Some attributes are directly accessible as properties. This is true for ID, href, and value attributes.

You can check for the existence of an attribute using the hasAttribute method as seen in the example below.

if (document.querySelector("a").hasAttribute("target")) {
    console.log("The first link has a target attribute.");
} else {
    console.log("The first link does not have a target attribute.");


In a web page, a tag can have multiple classes. classList retrieves a DOM element's list of classes for a given DOM element.

// List of classes of the element identified by "ancient"
var classes = document.getElementById("ancient").classList;
console.log(classes.length); // Will be 1, since the element only has one class.

You also have the opportunity to test the presence of a class on an element by calling contains and passing it a parameter.

if (document.getElementById("ancient").classList.contains("wonders")) {
    console.log("The element identified by 'ancient' also has the class 'wonders'.");
} else {
    console.log("The element identified by 'ancient' does not have the class 'wonders.'");

In summary

  •  Rather than go through the DOM node by node, you can quickly access one or more elements using selection methods.

  • The getElementsByTagName,getElementsByClassName, and getElementByIdmethods respectively search items by tag name, class, and ID. The first two methods return a list, and the latter returns a single item.

  • The querySelectorAll and querySelector methods make it possible to search for items using a CSS selector. The first method returns all matching items, and the second returns only the first.

  • The innerHTML property returns the HTML content of an element. The textContentproperty returns its textual content without HTML markup.

  • The getAttribute and hasAttribute methods allow access to element attributes.

  • classList provides access to classes of an element.

Example of certificate of achievement
Example of certificate of achievement