Count the Elements in a Div using JavaScript

avatar

Borislav Hadzhiev

Sun Jan 09 20222 min read

Count the Elements in a Div using JavaScript #

To count the elements in a div:

  1. Select the div element.
  2. Call the getElementsByTagName() method on the div, passing it an asterisk as a parameter.
  3. Access the length property on the collection.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <span> <p>Nested child 1</p> </span> <span> <p>Nested child 2</p> </span> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); const allChildren = box.getElementsByTagName('*').length; console.log(allChildren); // ๐Ÿ‘‰๏ธ 4 const directChildren = box.children.length; console.log(directChildren); // ๐Ÿ‘‰๏ธ 2

We used the document.getElementById method to select the div element.

The Element.getElementsByTagName method returns a collection containing the elements with the provided tag name, scoped to the element the method was called on.

Instead of passing a specific tag name to the method, we passed it an asterisk * as a parameter.

The special string that contains an asterisk "*" represents all elements.

This includes all of the nested descendants of the div element.

The getElementsByTagName method returns an HTMLCollection, on which we can access the length property to get the number of matching elements.

If you need to get the count of the direct children of the div element, use the children property to get a collection of the element's direct children.

The children property includes only element nodes.

When accessed on the div element, the children property returns a collection of the span elements.

index.html
<div id="box"> <span> <p>Nested child 1</p> </span> <span> <p>Nested child 2</p> </span> </div>

When we access the length property on the collection, we get back a value of 2.

It should be noted that the children property includes only element nodes. If you need to get a collection that includes text and comment nodes, use the childNodes property instead.
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> <span> <p>Nested child 1</p> Some text <!-- A comment --> </span> <span> <p>Nested child 2</p> </span> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const box = document.getElementById('box'); const directChildren = box.childNodes.length; console.log(directChildren); // ๐Ÿ‘‰๏ธ 5 // ๐Ÿ‘‡๏ธ [text, span, text, span, text] console.log(box.childNodes);

The childNodes property returns a NodeList that contains child elements, text nodes and comments.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee