Javascript DOM HTML Document getElementsByTagName() Method count elements

Introduction

Find out how many <li> elements there are in the document using the length property of the HTMLCollection object:

var x = document.getElementsByTagName("LI").length;

Click the button to find out how many li elements there are in this document.

View in separate window

<!DOCTYPE html>
<html>
<body>
<p>An unordered list:</p>
<ul>
  <li>CSS</li>
  <li>HTML</li>
  <li>Java</li>
</ul>/*from   ww  w .  j  a  v a2 s .co m*/
<button onclick="myFunction()">Test</button>

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

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

</body>
</html>



PreviousNext

Related