The DOM Selectors: Element by Class, ID, and Tag
Table of Contents
Introduction
The Document Object Model (DOM) is a programming interface for web documents, representing the page structure as a tree. DOM selectors allow developers to dynamically interact with and manipulate webpage elements. This article explores three powerful methods: getElementsByTagName, getElementsByClassName, and getElementById.
Content
1. getElementsByTagName
Description: Retrieves all elements with a specified tag name. Returns a live HTMLCollection that updates if the document changes.
Syntax:
1 |
let elements = document.getElementsByTagName('tagName'); |
Example:
1 2 3 |
// Select all <h2> elements in the document let elements = document.getElementsByTagName('h2'); console.log(elements); |
Explanation: In the HTML file, the following elements are selected:
1 2 |
<h2 id="greeting">Hello World</h2> <h2>Welcome</h2> |
2. getElementsByClassName
Description: Retrieves elements with the specified class name, returning an HTMLCollection.
Syntax:
1 |
let elements = document.getElementsByClassName('className'); |
Example:
1 2 3 |
// Select all elements with the class 'para' let elements = document.getElementsByClassName('para'); console.log(elements[0]); |
Explanation: The following elements are selected:
1 2 |
<p class="para">This is the para with class</p> <b class="para">This is the second para with class</b> |
3. getElementById
Description: Targets a single element by its unique ID, returning the element or null if no match is found.
Syntax:
1 |
let element = document.getElementById('idName'); |
Example:
1 2 3 |
// Select the element with ID 'greeting' let element = document.getElementById('greeting'); console.log(element); |
Explanation: The following element is selected:
1 |
<h2 id="greeting">Hello World</h2> |
Comparison Table
Selector Method | Input Type | Returns | Use Case |
---|---|---|---|
getElementsByTagName | Tag name | HTMLCollection | When selecting all elements of a specific tag |
getElementsByClassName | Class name | HTMLCollection | When selecting elements with a shared class |
getElementById | ID (unique) | Single DOM element | When targeting a unique element by ID |
Conclusion
DOM selectors are essential tools for dynamic web interactions. By mastering methods like getElementsByTagName, getElementsByClassName, and getElementById, developers can efficiently manipulate DOM elements, creating responsive and interactive web pages.