Javascript DOM HTML NodeList length Property style children element

Introduction

Loop through all <p> elements inside a <div> element, and change the background color of each <p>:

Click the button to change the background color of all p elements inside the div element.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {//from ww  w .j a  va2 s.com
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
  <p>First p element in div.</p>
  <p>Another p element in div.</p>
  <p>A third p element in div.</p>
</div>
<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
  var div = document.getElementById("myDIV");
  var nodelist = div.getElementsByTagName("P");

  var i;
  for (i = 0; i < nodelist.length; i++) {
    nodelist[i].style.backgroundColor = "red";
  }
}
</script>

</body>
</html>



PreviousNext

Related