Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
16

The problem is:



start = document.getElementById(startID).tagName;

while (start.parentNode) {
start = start.parentNode;


You trying to get the parentNode from the tagName, which is a string.
Remove the tagName, and you should be fine.


[#79787] Tuesday, March 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;