Interactive online courses HTML Academy
2026-03-09 14:09 Diff

We included our script in another news story, where there turned out to be four buttons. We clicked on them, but only the first two worked, since they were the only ones we added event handlers to. How can that be? Do we really have to create a separate script for each news story and copy the handlers? Of course not. Use a loop instead.

A loop is a statement that allows you to execute code several times. There are various types of loops in JavaScript. We will learn about them in future chapters. For our assignment we need the for of loop:

for (of collection variable) { // Code that must be executed several times }

The for of loop will execute the code in the curly braces as many times as there are elements in the collection indicated in parentheses. Each such repetition is called an iteration.

When a loop is created in parentheses, you must also specify a variable. Usually in order to do this, a new variable is declared, and it is used only inside the loop. At each iteration, JavaScript will automatically write the next element in the collection to this variable.

Consider the following example:

let elements = document.querySelectorAll('p'); // Find all paragraphs for (let element of elements) { // Create a loop and variable console.log(element); // Output the elements to the console }

If the elements collection contains two elements, then JavaScript will execute the following instructions:

// First iteration: // The first element of the collection is automatically written to the variable. element = elements[0]; // The code from the loop is executed – The first element of the collection is displayed in the console. console.log (element); // Second iteration: // The second element of the collection is automatically written to the variable element = elements[1]; // The code from the loop is executed again, but now the second element is output to the console. console.log(element);

The loop is complete when the elements in the collection are finished. After that, JavaScript will proceed to execute the instructions that come after the loop.

Thanks to the loop, we don’t need to know the number of elements in the collection and to copy the handlers in advance. This helps us to make the script universal and the code more concise and understandable.

Test how it works: create a loop and tell JavaScript to output all of the elements in the tooltipButtons collection to the console.