Length: 10 minutes
Summary
let elements = document.querySelectorAll('selector');
Details
To select multiple elements, you can use the querySelectorAll()
method. Just like the querySelector()
method, you usually use it on the document
object.
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
let elements = document.querySelectorAll('li');
You can treat this list of elements like an array. To select a specific element, use square brackets, like this:
let elements = document.querySelectorAll('li');
// first element
elements[0]
// second element
elements[1]
To perform an action on all of the elements in the list, you can use a loop, like this:
let elements = document.querySelectorAll('li');
for (const element of elements) {
console.log(element);
}
Demo
Exercises
Try adding the code in the last snippet with the loop to your main.js
file.