Element querySelectorAll() Method - Get all <p> elements inside a <div> element, and set the background color of the first <p> element (index 0): - Javascript DOM

Javascript examples for DOM:Element querySelectorAll

Description

Element querySelectorAll() Method - Get all <p> elements inside a <div> element, and set the background color of the first <p> element (index 0):

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {//from  w  w  w .  j  a v  a2s . com
    border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
  <p>This is a p element in div.</p>
  <p>This is also a p element in div.</p>
</div>

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

<script>
function myFunction() {
    var x = document.getElementById("myDIV").querySelectorAll("p");
    x[0].style.backgroundColor = "red";
}
</script>

</body>
</html>

Related Tutorials