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

Advertisements

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: