38

I have a div with span inside of it. Is there a way of counting how many elements in a div then give it out as a value. For Example there were 5 span in a div then it would count it and alert five. In Javascript please.

Thank you.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118

9 Answers9

54

If you want the number of descendants, you can use

var element = document.getElementById("theElementId");
var numberOfChildren = element.getElementsByTagName('*').length

But if you want the number of immediate children, use

element.childElementCount

See browser support here: http://help.dottoro.com/ljsfamht.php

or

element.children.length

See browser support here: https://developer.mozilla.org/en-US/docs/DOM/Element.children#Browser_compatibility

Oriol
  • 274,082
  • 63
  • 437
  • 513
24

You can use this function, it will avoid counting TextNodes. You can choose to count the children of the children (i.e. recursive)

function getCount(parent, getChildrensChildren){
    var relevantChildren = 0;
    var children = parent.childNodes.length;
    for(var i=0; i < children; i++){
        if(parent.childNodes[i].nodeType != 3){
            if(getChildrensChildren)
                relevantChildren += getCount(parent.childNodes[i],true);
            relevantChildren++;
        }
    }
    return relevantChildren;
}

Usage:

var element = document.getElementById("someElement");
alert(getCount(element, false)); // Simply one level
alert(getCount(element, true)); // Get all child node count

Try it out here: JS Fiddle

Scott
  • 21,211
  • 8
  • 65
  • 72
  • No problem, you're welcome. If this solves the issue don't forget to mark it as the answer. If you need further explanation of how it works let me know. – Scott Sep 02 '12 at 17:07
9

Without jQuery:

var element = document.getElementById("theElementId");
var numberOfChildren = element.children.length

With jQuery:

var $element = $(cssSelectocr);
var numberOfChildren = $element.children().length;

Both of this return only immediate children.

Some Guy
  • 15,854
  • 10
  • 58
  • 67
Chango
  • 6,754
  • 1
  • 28
  • 37
4

i might add just stupid and easy one answer

<div>this is div no. 1</div>
<div>this is div no. 2</div>
<div>this is div no. 3</div>

you can get how many divs in your doc with:

const divs = document.querySelectorAll('div');
console.log(divs.length) // 3
Safwat Fathi
  • 758
  • 9
  • 16
2

With jQuery you can do like this:

var count = $('div').children().length;
alert( count );​​​

Here's a Fiddle: http://jsfiddle.net/dryYq/1/

Krycke
  • 3,106
  • 1
  • 17
  • 21
  • This will fail when there are nested elements in the div – Andreas Köberle Sep 02 '12 at 16:16
  • 4
    Where in the question do you see that the OP is using jQuery? – jfriend00 Sep 02 '12 at 16:18
  • @jfriend00 I didn't, but as this was a javascript question, I thought that a jQuery answer could fit, if the questioner happened to use jQuery. – Krycke Sep 02 '12 at 17:22
  • The general mode on StackOverflow is that you only propose a jQuery answer if the question is tagged with jQuery. Otherwise, you do plain javascript (not using pre-built libraries). In otherwords, if the OP wants jQuery answers, they tag the question as such. If not, we assume plain javscript. – jfriend00 Sep 02 '12 at 17:24
  • @user1572008 Nice to here. If you like it, please mark it as an Accepted Answer :) – Krycke Sep 02 '12 at 17:28
2

With jQuery; checks only for spans inside a div:

JSFiddle

$(function(){
    var numberOfSpans = $('#myDiv').children('span').length;
    alert(numberOfSpans);
})();​
dakab
  • 5,379
  • 9
  • 43
  • 67
Sandeep G B
  • 3,957
  • 4
  • 26
  • 43
2

To count all descendant elements including nested elements in plain javascript, there are several options:

The simplest is probably this:

var count = parentElement.getElementsByTagName("*").length;

If you wanted the freedom to add more logic around what you count, you can recurse through the local tree like this:

function countDescendantElements(parent) {
    var node = parent.firstChild, cnt = 0;
    while (node) {
        if (node.nodeType === 1) {
            cnt++;
            cnt += countDescendantElements(node);
        }
        node = node.nextSibling;
    }
    return(cnt);
}

Working Demo: http://jsfiddle.net/jfriend00/kD73F/

If you just wanted to count direct children (not deeper levels) and only wanted to count element nodes (not text or comment nodes) and wanted wide browser support, you could do this:

function countChildElements(parent) {
    var children = parent.childNodes, cnt = 0;
    for (var i = 0, len = children.length; i < len; i++) {
        if (children[i].nodeType === 1) {
            ++cnt;
        }
    }
    return(cnt);
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
2

The easiest way is to select all the span inside the div which will return a nodelist with all the span inside of it... Then you can alert the length like the example below.

alert(document.querySelectorAll("div span").length)
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ahmed Mansour
  • 500
  • 4
  • 14
0

ALTERNATIVE: If you want to count elements in a div from a browser then you do not need to write any javascript code in the console since the count is already displayed:

  • Firefox: Right click on the div element and select 'Show DOM properties'. Then search for childElementCount and childNodes to inspect your counts.

  • Chrome: Just normal click on the div element and on the side view window (where the Style is usually displayed) select the 'Properties' tab instead. The childElementCount and childNodes will be there as well.