0 added
0 removed
Original
2026-01-01
Modified
2026-03-09
1
<p>We obtained a collection of two elements and output it to the console. The found elements are buttons, and when we click on each of them a pop-up with a tooltip should appear. To do this, we need to add an event handler to each button in the collection. How can we tell JavaScript that we want to do something with a collection element? We can address this element using an index.</p>
1
<p>We obtained a collection of two elements and output it to the console. The found elements are buttons, and when we click on each of them a pop-up with a tooltip should appear. To do this, we need to add an event handler to each button in the collection. How can we tell JavaScript that we want to do something with a collection element? We can address this element using an index.</p>
2
<p>The index is the serial number of the element in the collection. Notice how this number is counted from zero, so the first element has an index of 0 and the second one has an index of 1. Indices are written in square brackets after the collection name:</p>
2
<p>The index is the serial number of the element in the collection. Notice how this number is counted from zero, so the first element has an index of 0 and the second one has an index of 1. Indices are written in square brackets after the collection name:</p>
3
collection[index]<p>The way we access elements by index is similar to the way we access variables by name:</p>
3
collection[index]<p>The way we access elements by index is similar to the way we access variables by name:</p>
4
let elements = document.querySelectorAll('p'); console.log(elements[0]); // Displays the first element in the collection. console.log(elements[1]); // Displays the second element in the collection.<p>Let’s practice: We will first output the first found button to the console and then the second one.</p>
4
let elements = document.querySelectorAll('p'); console.log(elements[0]); // Displays the first element in the collection. console.log(elements[1]); // Displays the second element in the collection.<p>Let’s practice: We will first output the first found button to the console and then the second one.</p>