Nearby lessons

4 of 14

JavaScript DOM Targeting Methods

πŸ“Œ What are DOM Targeting Methods?

To manipulate HTML elements using JavaScript, we must first select them. JavaScript provides several DOM methods to find elements by their ID, class name, tag name, or CSS selectors. These methods help developers access specific parts of the web page and perform operations like updating content, styling, or adding events.

πŸ” getElementById()

The getElementById() method selects a single HTML element by its unique id. If more than one element has the same ID (which is invalid), only the first one is selected. If no element is found, it returns null.

Syntax:
document.getElementById("element_ID")

Code Example
PREVIEW READY
Loading Editor...
Live Preview

πŸ“¦ getElementsByClassName()

The getElementsByClassName() method returns a live HTMLCollection of all elements with the specified class name. You can access them using an index.

Syntax:
document.getElementsByClassName("className")

Code Example
PREVIEW READY
Loading Editor...
Live Preview

πŸ”– getElementsByTagName()

The getElementsByTagName() method returns all elements with a given tag name. You can loop through them using their index.

Syntax:
document.getElementsByTagName("tagName")

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🎯 querySelector()

The querySelector() method returns the first element that matches a CSS selector. It works with IDs, classes, tags, and more complex CSS rules.

Syntax:
document.querySelector("selector")

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🎯 querySelectorAll()

The querySelectorAll() method returns all elements that match a CSS selector as a NodeList. You can loop through it to apply changes.

Syntax:
document.querySelectorAll("selector")

Code Example
PREVIEW READY
Loading Editor...
Live Preview

🧠 Test Your Knowledge

5 Questions

Progress: 0 / 5
Keep Going!JavaScript DOM - Changing HTML