One way to achieve this is by using the document.getElementsByClassName
method, which returns an HTMLCollection
containing all elements with a specific class name (as opposed to just one Element
). You can easily convert this HTMLCollection
into an array using the spread syntax [...x]
.
If you need to find the sum of child elements within all parent elements with the class .myClass
:
[...document.getElementsByClassName('myClass')]
.reduce((sum, parent) => sum += parent.childElementCount, 0);
Another option is to use the newer and more concise document.querySelector[All]
methods:
[...document.querySelectorAll('.myClass')]
.reduce((sum, parent) => sum += parent.childElementCount, 0);