Find out how many <p> elements there are in the document:
var nodelist = document.getElementsByTagName("P").length;
Click the button to find out how many p elements there are in this document.
<!DOCTYPE html> <html> <body> <p>The first p element in the document.</p> <p>Another p element.</p> <button onclick="myFunction()">Test</button> <p id="demo">I am also a p element.</p> <script> function myFunction() {// w w w. j a v a 2 s .c o m var nodelist = document.getElementsByTagName("P").length; document.getElementById("demo").innerHTML = nodelist; } </script> </body> </html>
The length property returns the number of nodes in a NodeList object.
The length property is useful when you want to loop through the nodes in a node list.
This property is read-only.
We can use the item()
method to return a node at the specified index in a NodeList object.