Sometimes I come across the need to count the number of child elements in any given area of the DOM. Below is an example of how to count the number of elements by using the getElementsByTagName() function.
<html>
<head>
<script language = "Javascript">
function countChildElements(parent, child)
{
var parent = document.getElementById(parent);
var childCount = parent.getElementsByTagName(child).length;
alert(childCount);
}
</script>
</head>
<body>
<ul id = "listing">
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
</ul>
<input type = "button" value = "Count <li>" onClick="countChildElements('listing','li');" />
</body>
</html>
When you click the button, the browser will alert you to the number of child <li> elements to the “listing” <ul>.
February 12, 2008 at 2:41 am |
Thanks for this! I’ve been looking for something like this for days!
June 11, 2008 at 2:13 am |
Although this looks good, it does not work if you’re HTML has nested LI items
like this:
List Item 1
nested item
List Item 2
List Item 3
July 23, 2008 at 3:44 am |
Be carefull with using “parent” as variable name.
“parent” is global.