PDA

View Full Version : Ancestor Function



blm126
08-19-2006, 10:14 PM
I am trying to write an "ancestor function". it will take three values child parent and stop. All three are elements. The purpose is to check whether child is located under parent in the DOM. It should only search until it reachs stop(or the parent).It will then return true or false accordingly. I hope that makes sense. Here's my attempt.


function ancestor(child,parent,stop){
if(child.parentNode){
while(child != stop){
if(child.parentNode == parent){
return true;
}
else{
child = child.parentNode;
}
}
}
return false;
}

Unfortunately, I can't get it working. The firefox error console says "child has no properties"(references bolded line). Any help is appreciated as I really need this function to work(I can't think of any other way)

blm126
08-19-2006, 10:31 PM
Never Mind, I figured it out. Here's the working one if you need it



function ancestor(child,parent,stop){
if(child.parentNode){
while(child != stop){
if(child.parentNode){
if(child.parentNode == parent){
return true;
}
else{
child = child.parentNode;
}
}
else{
return false;
}
}
}
return false;
}

If anyone has a better way to do this I would be happy to here it.

Twey
08-19-2006, 10:42 PM
Blimey... I've heard of verbosity but that takes the biscuit :p
function ancestor(child, parent, stop) {
for(; child.parentNode && child !== stop; child = child.parentNode)
if(child.parentNode === parent) return true;
return false;
}

blm126
08-19-2006, 11:02 PM
And that, is why no one should ever trust my advice. :)