Loop through the nodes of a NodeList object and change the background color of all <p> elements in the list: - Javascript Statement

Javascript examples for Statement:for

Description

Loop through the nodes of a NodeList object and change the background color of all <p> elements in the list:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<h2>This is a h2 element</h2>

<p>This is a p element</p>

<p>This is also a p element.</p>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {//  www .j av a 2  s  . c o  m
    var myNodelist = document.getElementsByTagName("P");
    var i;
    for (i = 0; i < myNodelist.length; i++) {
        myNodelist[i].style.backgroundColor = "red";
    }
}
</script>

</body>
</html>

Related Tutorials