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…


This content originally appeared on DEV Community and was authored by Christopher Ninman

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')

or

document.querySelector('#element-id')

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'

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'

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')

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

document.getElementsByClassName('element-class')

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

document.querySelectorAll('.element-class')

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]}`);
  }
}

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

allButtons[5].className = 'delete-button'

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')

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");

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


This content originally appeared on DEV Community and was authored by Christopher Ninman


Print Share Comment Cite Upload Translate Updates
APA

Christopher Ninman | Sciencx (2021-11-08T21:50:26+00:00) DOM Selectors in JavaScript. Retrieved from https://www.scien.cx/2021/11/08/dom-selectors-in-javascript/

MLA
" » DOM Selectors in JavaScript." Christopher Ninman | Sciencx - Monday November 8, 2021, https://www.scien.cx/2021/11/08/dom-selectors-in-javascript/
HARVARD
Christopher Ninman | Sciencx Monday November 8, 2021 » DOM Selectors in JavaScript., viewed ,<https://www.scien.cx/2021/11/08/dom-selectors-in-javascript/>
VANCOUVER
Christopher Ninman | Sciencx - » DOM Selectors in JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/08/dom-selectors-in-javascript/
CHICAGO
" » DOM Selectors in JavaScript." Christopher Ninman | Sciencx - Accessed . https://www.scien.cx/2021/11/08/dom-selectors-in-javascript/
IEEE
" » DOM Selectors in JavaScript." Christopher Ninman | Sciencx [Online]. Available: https://www.scien.cx/2021/11/08/dom-selectors-in-javascript/. [Accessed: ]
rf:citation
» DOM Selectors in JavaScript | Christopher Ninman | Sciencx | https://www.scien.cx/2021/11/08/dom-selectors-in-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.