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
2010-01-29 11:45:13
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.
slashnick
2010-01-29 11:47:33
Not just in Mozilla. This is correct behaviour; it's IE that gets it wrong.
bobince
2010-01-29 12:35:11
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
2010-10-25 07:04:57