DEV Community

Cover image for DOM Selectors in JavaScript
Christopher Ninman
Christopher Ninman

Posted on

DOM Selectors in JavaScript

While creating interactive content with JavaScript, you will often find yourself needing to access various HTML elements in order to make changes to them. We'll go through some of the main ways you can grab elements in the DOM, and how you can make use of what they hold.

Different Types of Selectors

ID

If you want to manipulate one single element, the easiest and most straight-forward approach is to find that element by id. Only one HTML element can have a specific id attribute, and each ID is unique to one element.

Class

Multiple elements can be grouped together when they are given the same class name. An example would be if you have multiple buttons that serve the purpose of deleting content, and you want all of those buttons to be manipulated in the same manner.

Tag

Some common tags in HTML are body, h1, p, div, span, and img, though there are numerous others. Another DOM selector is tagName, which selects elements based on the type of element they are.

Accessing an Element by ID

In order to access an element with a specific id, you have a few options. You can either use:

document.getElementById('element-id')
Enter fullscreen mode Exit fullscreen mode

or

document.querySelector('#element-id')
Enter fullscreen mode Exit fullscreen mode

Either option will search the entire document and return the element with a matching id as an object. If no element with the given id is found, null will be returned. If you encounter a TypeError: Cannot read properties of null, it is likely that no element with that id was found.

You can also use these methods to create a variable, and then manipulate the DOM by calling that variable.

let foundElement = document.getElementById('first-header')
foundElement.style.color = 'blue'
Enter fullscreen mode Exit fullscreen mode

If an element does not exist in the HTML file and is created using JavaScript, you can still give that element an id using JavaScript with the following syntax:

let createdWithJsElement = document.createElement('p')
createdWithJsElement.id = 'js-element'
Enter fullscreen mode Exit fullscreen mode

Accessing an Element by ClassName

Similar to accessing an element by id, you have a few choices for selecting elements by class. You can access elements by class name with the following methods.

document.querySelector('.element-class')
Enter fullscreen mode Exit fullscreen mode

This will return only the first element that matches the specified class name.

document.getElementsByClassName('element-class')
Enter fullscreen mode Exit fullscreen mode

The use of getElementsByClassName will return a live HTMLCollection of all the elements matching that class.

document.querySelectorAll('.element-class')
Enter fullscreen mode Exit fullscreen mode

Using the querySelectorAll method will return a static NodeList of all the elements matching that class. Distinguishing between a NodeList and an HTMLCollection is a whole other topic which you can explore here.

Note the use of a dot prior to the class name, as opposed to the hash-tag prior to doing a query selector on an id.

In order to manipulate every element that is returned from the getElementsByClassName or querySelectorAll methods, you'll need to run a for loop to iterate the array-like object and make the desired changes to each element.

let allButtons = document.getElementsByClassName('button')

function testButtons () {
  for (let i = 0; i < allButtons.length; i++) {
    console.log(`I am button ${[i+1]}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

You can create or change an element's class, or other attribute, by accessing that element by its [index].

allButtons[5].className = 'delete-button'
Enter fullscreen mode Exit fullscreen mode

Accessing an Element by TagName

Yet another way to select elements in the DOM is to select the elements by their tag name.

let allParagraphs = document.getElementsByTagName('p')
Enter fullscreen mode Exit fullscreen mode

You can get even more specific with your search for specific elements based on tag name. Suppose you want to change the color of the text in all the paragraphs of a "Skills" section. You can search for elements by tag name within a specific div.

const mySkills = document.getElementById("skills-div");
const skillParagraphs = mySkills.getElementsByTagName("p");
Enter fullscreen mode Exit fullscreen mode

Like when the getElementsByClassName method is called, getElementsByTagName will return a live HTML collection of elements. This can be iterated over with a for loop just like the list of elements gathered with the getElementsByClassName method.

Wrapping It Up

If you can't precisely locate elements, you'll have difficulty making your JavaScript code come to life. These selectors are just the tip of the iceberg for making your creations dynamic.

Photo by Max Duzij on Unsplash

Top comments (0)