By the end of this lesson, learners will be able to:
getElementById()getElementsByClassName()querySelector()querySelectorAll()Before you can change or interact with an HTML element using JavaScript, you must first select it from the DOM.
Think of it like this:
The DOM is a big tree. To change something on a branch (like a paragraph), you need to first find that branch.
getElementById(id)Selects one element by its unique id attribute.
javascriptKopierenBearbeitendocument.getElementById("element-id");
HTML:
htmlKopierenBearbeiten<h1 id="main-title">Welcome</h1>
JavaScript:
let heading = document.getElementById("main-title");
console.log(heading.textContent); // "Welcome"
This method always returns a single element or null.
getElementsByClassName(className)Selects all elements with a given class name.
document.getElementsByClassName("some-class");
HTML:
<p class="highlight">Item 1</p>
<p class="highlight">Item 2</p>
JavaScript:
let items = document.getElementsByClassName("highlight");
console.log(items.length); // 2
Returns an HTMLCollection (like an array, but not quite). You can access items with indexes: items[0].
querySelector(selector)Selects the first element that matches a CSS-style selector.
document.querySelector("css-selector");
<p class="info">Paragraph 1</p>
<p class="info">Paragraph 2</p>
let firstInfo = document.querySelector(".info");
console.log(firstInfo.textContent); // "Paragraph 1"
Use this for flexible selection — works with IDs (#id), classes (.class), or tags (p, div, etc.)
querySelectorAll(selector)Selects all elements matching the CSS selector.
document.querySelectorAll("css-selector");
let paragraphs = document.querySelectorAll(".info");
paragraphs.forEach(p => console.log(p.textContent));
Returns a NodeList, which can be looped using forEach().
| Method | Selects | Returns | Notes |
|---|---|---|---|
getElementById() | One element (by ID) | Element or null | Fast and simple |
getElementsByClassName() | All elements with class | HTMLCollection | No forEach() support directly |
querySelector() | First matching element | Element or null | Supports all CSS selectors |
querySelectorAll() | All matching elements | NodeList | Use forEach() to loop |
getElementById() for single itemsquerySelector() for flexibility (e.g., nested elements like div > p)querySelectorAll() and loop through the result