Nearby lessons
4 of 14JavaScript 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
π¦ 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
π 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
π― 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
π― 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")