我正在尝试编写一个函数,该函数需要一个 ID,然后遍历 DOM 以查看该项目是否是标签的子项。这应该不会太难,但是我parentNode
回来了undefined
?我错过了什么?
这是我的代码的简化版本...在此先感谢。
<!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>