views:

679

answers:

3

Simple question, I have an element which I am grabbing via elementById(). How do I check if it has any children?

+8  A: 

A couple of ways:

if (element.firstChild) {
    // It has at least one
}

or the hasChildNodes() function:

if (element.hasChildNodes()) {
    // It has at least one
}

or the length property of childNodes:

if (element.childNodes.length > 0) {
    // It has at least one
}

If you only want to know about child elements (as opposed to text nodes, attribute nodes, etc.), you may need a more thorough check:

var hasChildElements, child;
hasChildElements = false;
for (child = element.firstChild;
     child;
     child = child.nextSibling
    ) {

    if (child.nodeType == 1) { // 1 == Element
        hasChildElements = true;
        break;
    }
}

All of this is part of DOM1, and nearly universally supported.

T.J. Crowder
A: 

You can check if the element has child nodes element.hasChildNodes(). Beware in Mozilla this will return true if the is whitespace after the tag so you will need to verify the tag type.

https://developer.mozilla.org/En/DOM/Node.hasChildNodes

slashnick
Not just in Mozilla. This is correct behaviour; it's IE that gets it wrong.
bobince
A: 
function uwtPBSTree_NodeChecked(treeId, nodeId, bChecked) { //debugger; var selectedNode = igtree_getNodeById(nodeId); var ParentNodes = selectedNode.getChildNodes(); var length = ParentNodes.length; if (bChecked) { /* if (length != 0) { for (i = 0; i

Govind Kumar Sahu