Page Content

Posts

How to Select DOM Elements with JavaScript

Selecting DOM Elements

Developers can access HTML elements and their attributes using JavaScript. Common methods include document.getElementById(), document.getElementsByTagName(), document.getElementsByClassName(), and document.querySelector()/querySelectorAll(). Once an element is selected, its attributes can be read using methods like getAttribute() or modified using setAttribute(). For many standard attributes, their values can also be accessed or set directly as properties of the element’s corresponding DOM object.

The document object, which represents the page, has numerous element selection methods. Three ways let you access items using HTML attributes: id, class, and tag name.

Getting Elements by ID

HTML elements are identified by their id attribute. This uniqueness lets document.getElementById() select one element. It finds an element with an id attribute matching the string and returns it. If no element with the ID exists, null is returned. Modern web development relies on this strategy to get the exact piece you require, independent of its position.

Here’s an example using an HTML snippet:

<!DOCTYPE html>
<html>
<body>
<div id=”one” class=”example”>Hi!</div>
<div id=”two” class=”example”>Hi again!</div>
</body>
</html>
<script>
// Select the div element with the ID “two”
console.log(document.getElementById(“two”)); //
// This would log the full HTML div with id=”two” to the console
</script>

As shown, document.getElementById(“two”) returns the <div id=”two”> element.

Getting Elements by Tag Name

Often, you must pick all elements of a specific type, such paragraphs (<p>) or list items (<li>). Specify the HTML tag name in document.getElementsByTagName(). This method returns an HTMLCollection, an array like object with all document elements with the supplied tag name in sequence. This method returns a collection because multiple elements can share a tag name.

You can access HTMLCollection elements by index, starting from 0, or item(). Collection length indicates the number of elements.

Importantly, element nodes have getElementsByTagName(). This allows you to call it on a given element (such a div acquired by getElementById) to get only its descendants with a certain tag name.

Consider an HTML snippet with multiple paragraph elements:

<!DOCTYPE html>
<html>
<body>
<h1>This is a heading</h1>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
</body>
</html>
<script>
// Select all p elements
const paragraphs = document.getElementsByTagName(“p”); //
console.log(paragraphs); // Outputs an HTMLCollection of p elements
console.log(paragraphs.length); // Shows the number of p elements
console.log(paragraphs.textContent); // Accesses the second paragraph’s text content (example from for innerHTML)
</script>

This code retrieves all <p> elements on the page as an HTMLCollection using document.getElementsByTagName(“p”).

Getting Elements by Class Name

Similar to selecting by tag name, you can pick all components that share a given CSS class using the document.getElementsByClassName() method. This method also returns an HTML Collection of all matching items. The string argument supplied to the method can be a single class name or a space separated list of class names; the method will return elements that possess all of the specified classes.

Like getElementsByTagName(), getElementsByClassName() can be used on individual element nodes to locate matched items exclusively inside their descendants.

Using an HTML snippet with elements sharing a class:

<!DOCTYPE html>
<html>
<body>
<div id=”one” class=”example”>Hi!</div>
<div id=”two” class=”example”>Hi again!</div>
<div id=”three” class=”something”>Goodbye!</div>
</body>
</html>
<script>
// Select all elements with the class “example”
const exampleElements = document.getElementsByClassName(“example”); //
console.log(exampleElements); // Outputs an HTMLCollection
console.log(exampleElements.textContent); // Accesses the content of the first element with class “example”
</script>

Document.getElementsByClassName(“example”) selects two example class div elements.

The HTMLCollections produced by getElementsByTagName() and getElementsByClassName() are “live”. After the collection is built, it will automatically update if elements that fit the selection criteria are added or removed from the document.

GetElementById, getElementsByTagName, and getElementsByClassName are powerful and often used methods for choosing elements, but also highlight the more versatile techniques document.querySelector(), document.querySelectorAll(). These approaches employ CSS selectors to target elements by tag name, ID (#), class name (.), attributes, and relationships. querySelector() returns the first matching element (or null), while querySelectorAll() returns a static NodeList with all matching elements. These techniques give you a complete arsenal for accessing almost any DOM element.

Querying DOM Elements

Find web page elements in the Document Object Model to interact with them using JavaScript. The DOM visualises HTML as a tree. Both document.querySelector() and document.querySelectorAll() select elements well.

These methods take CSS selector strings. This allows you to target elements by tag name, ID (#), class name (.), or sophisticated CSS patterns.

Using document.querySelector()

The document.querySelector() returns the first element matching the selector. Unmatched elements return null. You can use it when you only want one match or worry about the first one.

Here’s an example demonstrating querySelector() to select elements by tag name, ID, and class, referencing similar structures:

<!doctype html>
<html>
<head>
<title>Query Selector Example</title>
</head>
<body>
<h1>Main Heading</h1>
<div id=”unique-div” class=”content example”>First content block</div>
<p class=”content”>A paragraph</p>
<div class=”content”>Second content block</div>

<script>
// Select the first h1 element
const firstHeading = document.querySelector(“h1”);
console.log(“First h1:”, firstHeading); // Logs the <h1> element

// Select the element with the ID “unique-div”
const uniqueDiv = document.querySelector(“#unique-div”);
console.log(“Element with ID ‘unique-div’:”, uniqueDiv); // Logs the div with the specified ID

// Select the first element with the class “content”
const firstContent = document.querySelector(“.content”);
console.log(“First element with class ‘content’:”, firstContent); // Logs the first div
// Select the element with the class “example”
const exampleElement = document.querySelector(“.example”);
console.log(“Element with class ‘example’:”, exampleElement); // Logs the div with the class example

// Select an element that does not exist
const nonExistent = document.querySelector(“#non-existent”);
console.log(“Element with ID ‘non-existent’:”, nonExistent); // Logs null

</script>
</body>
</html>

The querySelector() method targets a single element using CSS selectors.

Using document.querySelectorAll()

The document.querySelectorAll() function retrieves all selector matched elements. Static NodeList is returned. The matching elements are in a NodeList array. You can iterate over its length. After creation, a static NodeList doesn’t update DOM changes. NodeLists are empty if no elements match.

Here’s an example using querySelectorAll() to select multiple elements by tag name and class:

<!doctype html>
<html>
<head>
<title>Query Selector All Example</title>
</head>
<body>
<h1>Heading 1</h1>
<p class=”intro”>This is the first paragraph.</p>
<h2>Heading 2</h2>
<p class=”content”>This is the second paragraph.</p>
<div class=”content”>A content div.</div>

<script>
// Select all p elements
const allParagraphs = document.querySelectorAll(“p”);
console.log(“All p elements:”, allParagraphs); // Logs a NodeList of p elements
console.log(“Number of p elements:”, allParagraphs.length); // Logs the count

// Select all elements with the class “content”
const contentElements = document.querySelectorAll(“.content”);
console.log(“Elements with class ‘content’:”, contentElements); // Logs a NodeList
console.log(“Number of content elements:”, contentElements.length);

// You can iterate through the NodeList
contentElements.forEach(element => {
console.log(“Content:”, element.textContent); // Access content of each element
}); //

// Select all h1, h2, and p elements
const headingsAndParagraphs = document.querySelectorAll(“h1, h2, p”); // Selects elements from a group
console.log(“All h1, h2, and p elements:”, headingsAndParagraphs);

</script>
</body>
</html>

In this example, querySelectorAll() returns elements that fit the criteria.

So, document.querySelector() and document.querySelectorAll() are crucial for locating DOM items using flexible CSS selectors. QuerySelector() returns the first match or a unique element (such by ID), while querySelectorAll() returns a static NodeList of all matching elements. Standard CSS selectors give them effective tools for choosing almost any web page element.

Index