Javascript DOM HTML Document querySelectorAll() Method by tag name

Introduction

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

Click the button to add a background color to the first p element whose index is 0 in the document.

View 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  ww.j a  v a 2 s. c  o m
  var x = document.querySelectorAll("p");
  x[0].style.backgroundColor = "red";
}
</script>

</body>
</html>



PreviousNext

Related