What are the different ways to select DOM elements in JavaScript?

Key takeaways:

  • JavaScript offers several methods to select and interact with DOM elements, each suited to different needs.

  • getElementById(): Selects a single element by its unique ID, returning the first matching element.

  • getElementsByTagName(): Selects all elements with a specified tag name, returning an HTMLCollection.

  • getElementsByClassName(): Selects all elements with a specified class name, returning an HTMLCollection.

  • getElementsByName(): Selects all elements with the same name attribute, returning a NodeList.

  • querySelector(): Selects the first element that matches a specified CSS selector, returning a single element.

  • querySelectorAll(): Selects all elements that match a specified CSS selector, returning a static NodeList.

JavaScript provides several ways to select and interact with elements in the Document Object Model (DOM), which is essential for manipulating web content dynamically. Knowing the different methods for selecting DOM elements can make our scripts more efficient and allow us to build interactive, responsive web applications. In this Answer, we’ll learn various methods to select DOM elements, understand the scenarios where each is most useful, and discuss how to use them with examples. Let’s dive in together!

Selecting DOM elements

Let’s say our elements are as follows:

  • HTML
  • CSS
  • JavaScript
A sample web application

JavaScript provides six methods to select an element from the document.

  • getElementById(): Search element by element_id.

  • getElementsByTagName(): Search element by tag name (e.g., span, div).

  • getElementsByClassName(): Search element by class name.

  • getElementsByName(): Search element by name attribute.

  • querySelector(): Returns the first element that matches the specified selector.

  • querySelectorAll(): Returns elements that match the specified selector.

What is the getElementById() method?

The getElementById() method is one of the simplest and most commonly used ways to select an element. This method retrieves the first element with the specified ID. Since IDs are unique in HTML, the getElementById() method returns only a single element.

Syntax

Here’s the syntax to use the getElementById() method:

document.getElementById("elementId");

This syntax allows us to specify the ID of the element we want to select. Since the ID of elements is supposed to be unique, this is a faster way to select an element. The getElementById() method is only available in the document object because, since id values must be unique, there is no need for a separate function.

If the ID is not found, then this method returns null.

Example

Here’s an example of using the getElementById() method:

  • HTML
  • CSS
  • JavaScript
Console
An example of the getElemenetById() method

In the above JavaScript code:

  • Line 1: We selected the <h1> element with the ID header.

  • Line 2: We logged the content of the heading to the console.

What is the getElementsByTagName() method?

The getElementsByTagName() method selects all elements with a given tag name (like div, p, button, etc.). It returns an HTMLCollection that we can iterate over.

Syntax

Here’s the syntax to use the getElementByTagName() method:

document.getElementsByTagName("tagName");

Unlike the getElementByID() method, the getElementsByTagName() method can be called on any element. If getElementsByTagName() is called upon an element, then only children of the element are searched. If we pass * (universal selector), then it selects all the elements.

Example

Here’s an example of using the getElementByTagName() method:

  • HTML
  • CSS
  • JavaScript
Console
An example of the getElemenetByTagName() method

In the above JavaScript code:

  • Line 1: We use the getElementsByTagName() method to select all <p> elements on the page.

  • Lines 3–5: We then logged the content of each paragraph using the for loop.

What is the getElementsByClassName() method?

The getElementsByClassName() method selects all elements with a specified class name and returns them as an HTMLCollection, which is an array-like object. We can access individual elements by their index.

Syntax

Here’s the syntax to use the getElementByClassName() method:

document.getElementsByClassName("className");

This syntax allows us to specify the class name of the element we want to select.

Example

Here’s an example of using the getElementByClassName() method:

  • HTML
  • CSS
  • JavaScript
Console
An example of the getElemenetByClassName() method

In the above JavaScript code:

  • Line 1: We retrieved all elements with the class list and stored it in the listItems.

  • Line 3–5: We then logged the content of each text box using the for loop.

What is the getElementsByName() method?

The getElementsByName() method selects elements by the name attribute, commonly used with form elements. It returns a NodeList of all matching elements.

Syntax

Here’s the syntax to use the getElementByName() method:

document.getElementByName("nameAttribute");

This syntax allows us to specify the attribute name of the element we want to select.

It is not recommended to use getElementByName() because it works differently on Internet Explorer.

Example

Here’s an example of using the getElementByName() method:

  • HTML
  • CSS
  • JavaScript
Console
An example of the getElemenetByName() method

In the above code:

  • Line 1: We use the getElementsByName("color") method to retrieve all radio buttons with the name color, enabling us to access their values.

  • Lines 3–5: We use the for loop to print the values to the console.

What is the querySelector() method?

The querySelector() method is more flexible, allowing us to use CSS selectors to find the first matching element. It’s powerful for selecting elements based on classes, IDs, attributes, and even descendant elements.

Syntax

Here’s the syntax to use the querySelector() method:

// using id selector
document.querySelector("#parent");
// using class selector
document.querySelector(".child"); //Returns first element in the document with class name
// using tagname
document.querySelector("div"); //Returns first div
// using tagname
document.querySelector("div span.child"); //Returns first span element with class name child, inside a div

The querySelector() method can be called on document and element. If no elements match the selector, null is returned.

SyntaxError is thrown when the CSS selector is invalid.

Example

Here’s an example of using the querySelector() method:

  • HTML
  • CSS
  • JavaScript
Console
An example of the querySelector() method

In the above JavaScript code:

  • Lines 1–2: We use the querySelector() to select the first <p> elements and log the item’s content to the console.

  • Lines 4–5: With querySelector(), we select the first <p> elements inside the first <div> and log the item’s content to the console.

What is the querySelectorAll() method?

The querySelectorAll() method is an extension of the querySelector() method. While querySelector() selects only the first matching element, querySelectorAll() selects all matching elements and returns a NodeList, which allows for easier iteration with array methods like forEach().

Syntax

Here’s the syntax to use the querySelectorAll() method:

document.querySelectorAll("selector");

The querySelectorAll() method returns static (non-live) NodeList Collection. The elements in NodeList are stored in the order present in the DOM. This method can be called on both document and element. If no matches are found, an empty NodeList is returned.

Example

Here’s an example of using the querySelectorAll() method:

  • HTML
  • CSS
  • JavaScript
Console
An example of the querySelectorAll() method

In the above JavaScript code:

  • Lines 1–4: We use the querySelectorAll() to select all <p> elements and used the forEach() loop to log each item’s content.

  • Lines 6–9: With querySelectorAll(), we select all <li> elements inside the <ul> and used the forEach() loop to log each item’s content.

Comparison of the selection methods

The table below provides a quick comparison between the selection methods, including its return type and a use case.

Method

Returns

Best use case

getElementById()

Single element

Selecting by a unique ID

getElementsByClassName()

HTMLCollection (array-like)

Multiple elements by class

getElementsByTagName()

HTMLCollection (array-like)

Multiple elements by tag

getElementsByName()

NodeList

Form elements with the same name attribute

querySelector()

Single element

First match with complex CSS selectors

querySelectorAll()

NodeList

All matches with complex CSS selectors

You can explore our JavaScript Catalog to learn everything from basics to advanced concepts!

Knowledge test

Let’s attempt a short quiz to assess your understanding.

1

Which method would you use to select the first element with a specific class?

A)

getElementsByClassName()

B)

getElementById()

C)

querySelector()

D)

getElementsByName()

Question 1 of 20 attempted

Conclusion

We’ve learned various ways to select DOM elements in JavaScript, from basic methods like getElementById() to more flexible options like querySelectorAll(). Choosing the right selection method can make the code cleaner and more efficient.


Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to check a DOM element in JavaScript?

To check or verify a DOM element in JavaScript, you can use methods like getElementById(), getElementsByClassName(), querySelector(), etc., depending on how you want to identify the element. After selecting the element, you can inspect it by logging it to the console or checking its properties.

Example:

const element = document.getElementById("myElement");
console.log(element); // Logs the element to the console

This will log the selected DOM element with the ID myElement. You can check its properties like textContent, style, className, etc.


How to get all DOM elements in JavaScript?

To get all DOM elements, you can use the getElementsByTagName() method or querySelectorAll(), which returns a collection or a NodeList of all matching elements.

  • getElementsByTagName() returns an HTMLCollection of all elements with the specified tag name.
  • querySelectorAll() returns a NodeList of all elements that match the specified CSS selector.

Example:

// Get all <p> elements
const allParagraphs = document.getElementsByTagName("p");
console.log(allParagraphs);

// Or using querySelectorAll for all elements
const allElements = document.querySelectorAll("*");
console.log(allElements);

How to select a specific element in JavaScript?

To select a specific element, you can use methods like getElementById(), getElementsByClassName(), querySelector(), or querySelectorAll(). These methods allow you to select elements based on their ID, class, tag name, or other attributes.

  • By ID: Use getElementById()
  • By class: Use getElementsByClassName() or querySelector()
  • By tag name: Use getElementsByTagName() or querySelector()
  • By attributes or complex selectors: Use querySelector()

Free Resources