HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

7) The Document Object Model Lesson

Select DOM Elements Using JavaScript

18 min to complete · By Ian Currie

Suppose you're looking to modify the text on your webpage using JavaScript, maybe in reaction to user inputs, and you need specific text to change accordingly. The initial step is to choose, or locate the correct element within the DOM. Similar to how you select text in a word processor for editing, this selection can be accomplished through different methods, such as .getElementById() and .querySelector(). Think of these as ways to search for the element you need.

In this lesson you'll cover a selection of Document methods that can be used to select elements from the DOM.

Understanding the DOM as an Object Hierarchy

Its good to think of the DOM as an object made up of objects. All of the elements in your HTML become an element object. Much like an array object, this allows you to call useful methods on it.

When the browser parses the HTML and creates the DOM, it structures everything like a tree. Every set of tags becomes a branch with as many sub branches as needed. Every branch, or node, has a parent. All nodes have parents apart from one, the root node, which is called document.

Use an ID to Select an Element with .getElementById()

One way of selecting an element is by using the .getElementById() method and passing the desired ID as an argument.

Illustration of a lighthouse

Every ID in your HTML should be unique. You can have more than one element with the same ID, but it's considered bad practice. The whole point of the id attribute is that it's meant to be unique. If you have more than one element with the same ID, you should be using a class instead.

For example if you have this very basic HTML:

<button id="mainBtn">Click Me</button>

<script>
  let btn = document.getElementById("mainBtn");
</script>

All that has happened in this file, is that the HTML has rendered the button and then run the script in between the <script> tags. This script assigned the button element, to a variable called btn. You've selected a DOM element!

If you save this HTML in a document and open it in a browser, you'll be able to interact with this btn element on the console:

btn; // <button id="mainBtn">Click Me</button>
btn.constructor.name; // HTMLButtonElement

You can see that the btn variable is an HTMLButtonElement object. This object has a lot of useful methods and properties that you can use to manipulate the element.

For example, you can change the text of the button by changing the innerText property:

btn.innerText = "Click Me Again";

If you run this on the console, you should see the button text update. Neat!

Use this method if you're looking to select a single element from the DOM that has a defined id attribute. This is a common way of selecting single elements from the DOM that are important.

.getElementById() can actually be called on any node, including the document (which is a type of Node) as you've seen in the examples. Calling it on a node will search for the child with the appropriate ID.

Use a CSS Selector to Select an Element with .querySelector()

Another way of selecting an element is by using the .querySelector() method and passing a CSS selector as an argument.

For example, if you have this HTML:

<button id="mainBtn">Click Me</button>

<script>
  let btn = document.querySelector("#mainBtn");
</script>

In this example, you've selected the same button as before, but this time you've used a CSS selector to do it. The CSS selector is #mainBtn, which is the same as the ID of the button. This is a very basic example, but you can use any CSS selector you like. This makes it incredibly flexible and useful.

Colorful illustration of a light bulb

If there are more than one elements on the page which would satisfy the CSS query selector, the .querySelector() method will only return the first one.

Here are some useful CSS selector examples you could use:

  • #mainBtn - Selects the element with the ID of mainBtn
  • .btn - Selects all elements with the class of btn
  • button - Selects all <button> elements
  • button.btn - Selects all <button> elements with the class of btn
  • button#mainBtn - Selects the <button> element with the ID of mainBtn
  • button.btn#mainBtn - Selects the <button> element with the ID of mainBtn and the class of btn
  • button.btn#mainBtn[disabled] - Selects the <button> element with the ID of mainBtn, the class of btn and the disabled attribute

As you can see, the .querySelector() method is very flexible and powerful. You can use any CSS selector you like to select elements from the DOM.

Colorful illustration of a light bulb

You might think that if .querySelector() can select any element, then there would be no need to use .getElementById(). However, there are valid reasons to prefer .getElementById() in certain cases:

  • It is faster than .querySelector(), although the difference is negligible for most uses.
  • It can be clearer and more direct, especially when you are simply selecting an element by its ID alone.
  • It's older than .querySelector(), so it's more widely supported in older browsers (but we're talking very old browsers at this point)

That said, many argue that using .querySelector() in projects is better because it gives you a standard way to do things. For beginners it can be easier to think of one method to "get" things from the DOM. Either way, it pays to be aware of both methods.

Use a CSS Selector to Select Multiple Elements with .querySelectorAll()

The .querySelectorAll() method works in a similar way to .querySelector(), but it returns an array-like object of all the elements that match the CSS selector.

For example, if you have this HTML:

<button id="mainBtn">Click Me</button>
<button id="secondBtn">Click Me Too</button>

<script>
  let btns = document.querySelectorAll("button");
</script>

In this example, you've selected all the buttons on the page. The CSS selector is button, which matches both buttons on the page.

If you were to interact with the btns variable on the console, you can get some more information about it:

btns; // NodeList(2) [button#mainBtn, button#secondBtn]

btns.length; // 2

btns[0]; // <button id="mainBtn">Click Me</button>
btns[1]; // <button id="secondBtn">Click Me Too</button>

btns.forEach((btn) => console.log(btn.innerText));
// Click Me
// Click Me Too

The object returned from .querySelectorAll() is a NodeList, which is array-like. This means that you can access the elements in the list using the square bracket notation, just like you would with an array. You can also use the .forEach() method to iterate over the elements in the list. However, not all array methods are available on a NodeList.

Other Ways to Select Elements

If you like, you can get away with just using .querySelector() and .querySelectorAll(). However, just like .getElementById() is more specific, there are other methods that can be used for specific tasks:

Method Name Arguments Return Value Description
.getElementsByClassName() className (string) HTMLCollection of elements Selects all elements with the specified class name.
.getElementsByTagName() tagName (string) HTMLCollection of elements Selects all elements with the specified tag name.
.getElementsByName() name (string) NodeList of elements Selects all elements with the specified name attribute.

You'll notice that .getElementsByClassName() and .getElementsByTagName() return an HTMLCollection of elements, whereas .getElementsByName() returns a NodeList of elements.

The difference between an HTMLCollection and a NodeList is that an HTMLCollection is live and a NodeList is static. This means that if you were to add or remove elements from the DOM, the HTMLCollection would update automatically, but the NodeList would not.

The HTMLCollection is more limited in it's methods than the NodeList, but you can still index into it using the square bracket notation, just like you would with an array. It also has a .length property, but it doesn't have a .forEach() like a NodeList.

How to Traverse the DOM

Sometimes it's not practical to select an element directly. For example, you might want to select an element based on its relationship to another element. In this case, you can use properties that locate nodes based on their relationship to other nodes:

| Property                  | Value                        | Description                                                       |
| ------------------------- | ---------------------------- | ----------------------------------------------------------------- |
| `.parentElement`          | `Element` or `null`          | Returns the parent element of the current element                 |
| `.children`               | `HTMLCollection` of elements | Returns a collection of the child elements of the current element |
| `.previousElementSibling` | `Element` or `null`          | Returns the previous sibling element of the current element       |
| `.nextElementSibling`     | `Element` or `null`          | Returns the next sibling element of the current element           |
| `.previousSibling`        | `Node` or `null`             | Returns the previous sibling node of the current node             |
| `.nextSibling`            | `Node` or `null`             | Returns the next sibling node of the current node                 |
| `.firstElementChild`      | `Element` or `null`          | Returns the first child element of the current element            |
| `.lastElementChild`       | `Element` or `null`          | Returns the last child element of the current element             |
Colorful illustration of a light bulb

A sibling node is a node that has the same parent.

The difference between previousElementSibling and previousSibling is in the types of nodes they return:

  1. .previousElementSibling:

    • This property returns the previous sibling of a node as an Element node.
    • It skips over any non-element nodes (like text nodes or comment nodes) and returns the nearest previous sibling that is an element (e.g., <div>, <span>, etc.).
  2. .previousSibling:

    • This property returns the previous sibling of a node, regardless of its node type.
    • This means it can return any type of node, including text nodes, comment nodes, or element nodes.

These methods can be very useful to locate DOM elements when you may not have a way to select them directly.

Summary: How to Select DOM Elements Using Javascript Selectors

You've already taken the first steps in DOM manipulation by learning how to select different elements on your webpage. In this lesson, you've:

  • Got to grips with how the DOM is structured—it's like a tree with nodes, and every element in your HTML is a part of this data structure.
  • Dived into using .getElementById() to select elements by their unique ID, which is a straight shot to identifying specific elements.
  • Discovered the power of .querySelector() for using CSS selectors to find elements, which is incredibly versatile as it can select any CSS query.
  • Explored .querySelectorAll() to fetch an array-like collection of nodes, allowing you to work with multiple elements that match your query.
  • Touched upon the difference between HTMLCollection and NodeList—the former is live and updates with the DOM, while the latter is static.

These tools are essential for creating dynamic, interactive web experiences that respond to user inputs and behaviors. Keep experimenting with them to get a feel for how they work in different scenarios!