About Lesson
Selecting Elements
To interact with elements in the DOM, you first need to select them. JavaScript provides a range of methods to target specific elements.
1. getElementById()
This method selects an element by its id attribute, which should be unique within the page. It returns a single element.
Example:
JavaScript
let heading = document.getElementById("main-title");
console.log(heading.textContent); // Output: Welcome to My Website
This method is efficient and straightforward, but it can only select one element since id is unique.
2. querySelector()
querySelector() is more flexible and can select elements using any CSS selector (#id, .class, or tag). It returns the first matching element.
Example:
JavaScript
let firstParagraph = document.querySelector("p");
console.log(firstParagraph.textContent);
3. querySelectorAll()
This method selects all elements that match a specific CSS selector and returns a NodeList, which is an array-like structure.
Example:
JavaScript
let listItems = document.querySelectorAll("li");
listItems.forEach(item => console.log(item.textContent)); // Loop through all <li> elements
You can loop over the NodeList using forEach to access each element individually.