Quick Answer: Count the Number of Child Elements in DOM

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>.

3 Responses to “Quick Answer: Count the Number of Child Elements in DOM”

  1. Katy Says:

    Thanks for this! I’ve been looking for something like this for days! :)

  2. pepie Says:

    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

  3. __ak Says:

    Be carefull with using “parent” as variable name.
    “parent” is global.

Leave a Reply