Document querySelectorAll() Method - Set the background color of all <p> elements in the document: - Javascript DOM

Javascript examples for DOM:Document querySelectorAll

Description

Document querySelectorAll() Method - Set the background color of all <p> elements in the document:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.example {//  w  ww.ja v  a2s . c om
    border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>

<h1>A h1 element</h1>

<div>A div element</div>

<p>A p element.</p>

<p>Another p element.</p>

<div class="example">
  <p>A p element inside a div element.</p>
</div>

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

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

</body>
</html>

Related Tutorials