Javascript DOM HTML Element querySelectorAll() Method get all <p> elements inside <div>

Introduction

Set the background color of all <p> elements in a <div> element:

Click the button to add a background color to all p elements inside DIV.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {/*w  w  w. j  a v  a 2s . c o m*/
  border: 1px solid black;
  margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
  <h2>A heading in div</h2>
  <p>A p element in div.</p>
  <p>Another p element in div.</p>
  <p>A p element with class="example" in div.</p>
</div>
<button onclick="myFunction()">Test</button>
<script>
function myFunction() {
  var x = document.getElementById("myDIV").querySelectorAll("p");
  var i;
  for (i = 0; i < x.length; i++) {
    x[i].style.backgroundColor = "red";
  }
}
</script>

</body>
</html>



PreviousNext

Related