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>
<html>
<head>
<script>
function changeText() {
var elements = document.getElementsByTagName("p");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "Paragraph " + (i + 1) + " has been changed";
}
}
</script>
</head>
<body>
<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>
<br><br>
<button onclick="changeText()">Change Text</button>
</body>
</html>
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.
+ There are no comments
Add yours