Document querySelectorAll() Method - Get all <p> elements in the document, and set the background color of the first <p> element (index 0): - Javascript DOM

Javascript examples for DOM:Document querySelectorAll

Description

Document querySelectorAll() Method - Get all <p> elements in the document, and set the background color of the first <p> element (index 0):

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

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

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

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

<script>
function myFunction() {//  w  w w .j ava  2  s.  c  om
    var x = document.querySelectorAll("p");
    x[0].style.backgroundColor = "red";
}
</script>

</body>
</html>

Related Tutorials