I'm trying to do a recursive function to find HTMLelement by class, but for some reason it stops after it reaches a child element without children. Here is the code:
var alpha = Obj.elementByClass(document.body, "message");
Obj.elementByClass = function(element, cl) {
var elementChildren = element.children,
elementChildrenLength = elementChildren.length;
for(var num=0; num<elementChildrenLength; num++) {
if(elementChildren[num].className && elementChildren[num].className.indexOf("cl") > -1) {
return elementChildren[num];
}
else if(elementChildren[num].children.length !=0) {
return Obj.elementByClass(elementChildren[num], cl);
}
}
};
Please don't advice jquery or other libraries, I would like to understand why it stops when it reaches the element without children.
Thanks!
else ifblock, youreturnsomething as soon as there is a child - but it may be possible that a child doesn't have any descendant with that specific class name. I recommend chceking whether the recursive call in theelse ifblock actually returns an element. As it is now, thereturnbreaks the wholeforloop.