6
rated 0 times
[
9]
[
3]
/ answers: 1 / hits: 18683
/ 11 Years ago, wed, march 6, 2013, 12:00:00
I'm trying to write a function that takes an ID then traverses up the DOM to see if that item is a child of a tag. This shouldn't be too hard however my parentNode
is coming back as undefined
? What am I missing?
Here's a simplified version of my code... thanks in advance.
<!DOCTYPE html>
<html lang=en>
<body>
<div id=top>
<div id=top2></div>
<div id=top3></div>
<div id=top4></div>
<div id=top5>
<div id=top5_1></div>
</div>
<div id=top6>
<div id=top6_1>
<a href= id=findMe>here I am...</a>
</div>
</div>
</div>
<script>
function findParent(startID, finish){
// change this from id to tag
start = document.getElementById(startID).tagName;
while (start.parentNode) {
start = start.parentNode;
if (start.tagName === finish){
console.log(true + startID + is a child of + finish);
}else{
console.log(false + startID + ISN'T a child of + finish);
}
}
}
findParent(findMe, BODY);
</script>
</body>
</html>
More From » dom