How to Use a For Loop to Iterate Through HTML Elements in JavaScript?

Estimated read time 2 min read

A for loop can be used to iterate through HTML elements in JavaScript, allowing you to perform operations on each element.

Here’s an example:

<!DOCTYPE html>
      function changeText() {
        var elements = document.getElementsByTagName("p");
        for (var i = 0; i < elements.length; i++) {
          elements[i].innerHTML = "Paragraph " + (i + 1) + " has been changed";
    <h1>Using a For Loop to Iterate Through HTML Elements in JavaScript</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <button onclick="changeText()">Change Text</button>

In this example, the JavaScript function changeText is defined and executed when the “Change Text” button is clicked. The function uses document.getElementsByTagName to select all the <p> elements and store them in a variable called elements. A for loop is then used to iterate through each element in the collection, and the innerHTML property is used to change the text of each <p> element. The loop counter i is used to keep track of the current element, and the length of the elements collection is used as the stop condition for the loop.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply