Javascript DOM HTML Document querySelector() Method by tag name and class name

Introduction

Get the first <p> element in the document with class="example":

document.querySelector("p.example");

Click the button to add a background color to the first p element in the document with class="example".

View in separate window

<!DOCTYPE html>
<html>
<body>

<h2 class="example">A heading with class="example"</h2>
<p class="example">A paragraph with class="example".</p>

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

<script>
function myFunction() {/*from ww w  . ja  v a  2 s. com*/
  document.querySelector("p.example").style.backgroundColor = "red";
}
</script>

</body>
</html>



PreviousNext

Related