Javascript DOM HTML Document querySelector() Method by tag name

Introduction

Get the first <p> element in the document:

document.querySelector("p");

Click the button to add a background color to the first p element 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() {/*from   w w  w. j a va  2 s. co m*/
  document.querySelector("p").style.backgroundColor = "red";
}
</script>

</body>
</html>



PreviousNext

Related