Javascript DOM HTML Document querySelectorAll() Method by class name

Introduction

Find out how many elements with class="example" there are in the document using the length property of the NodeList object:

var x = document.querySelectorAll(".example").length;

Click the button to find out how many elements with class "example" there are in this document.

View in separate window

<!DOCTYPE html>
<html>
<body>
<div class="example">
A div element with class="example"
</div>//  w w  w  .  ja  va 2s .  c  o m

<div class="example">
Another div element with class="example"
</div>

<p class="example">A p element with class="example"</p>
<button onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.querySelectorAll(".example");
  document.getElementById("demo").innerHTML = x.length;
}
</script>

</body>
</html>



PreviousNext

Related