In JavaScript, selecting elements from the DOM (Document Object Model) is essential to interact with and manipulate HTML content dynamically.

💡 Core Concept
Use DOM selection methods to access HTML elements so you can modify content, styles, or attributes.
Common Methods for Selecting Elements
Selection Methods Overview
| Method | Description |
|---|---|
getElementById(id) | Selects a single element by its unique id. |
getElementsByClassName(className) | Returns a live HTMLCollection of all elements with the given class. |
getElementsByTagName(tagName) | Returns a live HTMLCollection of all elements with the specified tag name. |
querySelector(selector) | Selects the first element that matches a CSS selector. |
querySelectorAll(selector) | Returns a static NodeList of all elements matching a CSS selector. |
Usage Highlights
getElementByIdis fastest but limited to one element.getElementsByClassNameandgetElementsByTagNamereturn live collections that update as the DOM changes.querySelectorandquerySelectorAllaccept any valid CSS selector, offering more flexibility.
⚠️ Important
Methods returning collections (getElementsByClassName, getElementsByTagName) return live lists; modifying the DOM may affect them dynamically.
📌 Deep Dive: Selecting Elements with querySelectorAll
JAVASCRIPT
const buttons = document.querySelectorAll('.btn.primary');
buttons.forEach(button => {
console.log(button.textContent);
});
Output
Logs text of all elements with both "btn" and "primary" classesWhen to Use Which Method?
- Use
getElementByIdwhen you know the element’s unique ID. - Use
querySelectorfor quick single element selection with complex selectors. - Use
querySelectorAllwhen selecting multiple elements with any CSS selector. - Use
getElementsByClassNameorgetElementsByTagNamefor faster selection by class or tag but with less selector flexibility.
💡 Tip
querySelector and querySelectorAll support all CSS selectors, making them versatile for complex selections.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
Which method selects the first element that matches a CSS selector?
Question 2 of 2
Which method returns a live HTMLCollection?
0/2
Loading results...