Count how many elements in a div

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


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.


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