How to count amount of child elements of a parent class

Viewed 321

I have something like this.

function myFunction() {
  var c = document.getElementById("myID").childElementCount;
  alert(c);
}

Is there a way to do something like this?

function myFunction() {
  var c = document.getElementsByClass("myClass").childElementCount;
  alert(c);
}
6 Answers

There's document.getElementsByClassName which returns an HTMLCollection (as opposed to a single Element). An HTMLCollection can be converted to an array easily with the [...x] syntax.

So if you want the sum of child elements in all .myClass parents:

[...document.getElementsByClassName('myClass')]
  .reduce((sum, parent) => sum += parent.childElementCount, 0);

There's also the newer and more concise document.querySelector[All] functions:

[...document.querySelectorAll('.myClass')]
  .reduce((sum, parent) => sum += parent.childElementCount, 0);

There is no getElementByClass but there is getElementsByClassName. However, it returns a collection of elements because you can have multiple elements with the same class. IDs however are limited to one per document.

So if you knew the index of the element in the collection, you could do something like this:

var els = document.getElementsByClassName('myClass');
var c = els[0].childElementCount;
alert(c);

If you would like to count all of the children of a certain className, here's how you would do that:

function countAllChildren(selector){
  let i = 0, q = document.querySelectorAll(selector);
  for(let n of q){
    i += n.children.length;
  }
  return i;
}
countAllChildren('.myClass');

did you tried

document.getElementsByClassName('myClass')[0].childElementCount

@evolutionxbox has the working answer even though it is a comment. @evolutionxbox please make your comment an answer so that I can mark yours as correct.

This works.

function myFunction() {
  var c = document.getElementsByClassName('myClass').length;
  alert(c);
}

You can use jquery for that:

var count = $("#myID").children().length;
Related