S08L03 – The DOM selectors – queryselectorAll


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:

Example:

Explanation: In the HTML file, the following elements are selected:

2. getElementsByClassName

Description: Retrieves elements with the specified class name, returning an HTMLCollection.

Syntax:

Example:

Explanation: The following elements are selected:

3. getElementById

Description: Targets a single element by its unique ID, returning the element or null if no match is found.

Syntax:

Example:

Explanation: The following element is selected:

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.