Lesson 42 - Selecting Elements in the DOM
When working with the Document Object Model (DOM), you need to select elements before modifying them. JavaScript provides several methods to target elements efficiently.
Explanation
To manipulate HTML elements, you first need to select them. JavaScript provides different ways to select elements based on their ID, class, tag name, or CSS selector.
Methods for Selecting Elements
1. getElementById()
– Selects an element by its id
.
let title = document.getElementById("main-title");
console.log(title);
- Returns the element with the specified
id
.
2. getElementsByClassName()
– Selects all elements with a given class (returns an HTMLCollection).
let items = document.getElementsByClassName("list-item");
console.log(items);
- Returns a collection of elements (not an array).
3. getElementsByTagName()
– Selects all elements of a specific tag name (returns an HTMLCollection).
let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs);
- Returns all
<p>
elements in the document.
4. querySelector()
– Selects the first element that matches a CSS selector.
let firstItem = document.querySelector(".list-item");
console.log(firstItem);
- Returns the first
.list-item
element.
5. querySelectorAll()
– Selects all elements that match a CSS selector (returns a NodeList).
let allItems = document.querySelectorAll(".list-item");
console.log(allItems);
- Returns all
.list-item
elements as a NodeList.
Example: Selecting and Changing Text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 42 - Selecting Elements</title>
</head>
<body>
<h2 id="main-title">Hello, DOM!</h2>
<p class="text">This is a paragraph.</p>
<ul>
<li class="list-item">Item 1</li>
<li class="list-item">Item 2</li>
<li class="list-item">Item 3</li>
</ul>
<script>
let title = document.getElementById("main-title");
title.textContent = "DOM Manipulation!"; // Change text
let items = document.querySelectorAll(".list-item");
items.forEach(item => item.style.color = "blue"); // Change text color
</script>
</body>
</html>
Try Your Hand
Steps:
- Create a file named
lesson42-selecting-elements.html
. - Write the Code above in the file.
- Save and Open the file in a browser.
- Modify it to:
- Change the heading color to red.
- Change all paragraph text to italic.
Experiment
- Select all
<div>
elements and change their background color. - Use
querySelectorAll()
to get all list items and add a border to them. - Use
getElementById()
to change an element’s font size.
Key Takeaways
getElementById()
selects a single element byid
.getElementsByClassName()
andgetElementsByTagName()
return HTMLCollections.querySelector()
selects the first matching element.querySelectorAll()
returns a NodeList of all matching elements.