3
我試圖編寫一個函數,它需要一個ID然後遍歷DOM來查看該項是否是標記的子項。這不應該太難,但我的parentNode
回來了undefined
?我錯過了什麼?爲什麼parentNode未定義?
這裏是我的代碼的簡化版本...在此先感謝。
<!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>
嘗試'start = document.getElementById(startID);' – alexbusu 2013-03-06 15:27:49
@ AlexanderV.B。 'startID'是一個變量。錯誤是在哪一行? 'while(start.parentNode)'這裏? – 2013-03-06 15:28:23
您可以使用'$('#'+ startID).parent('#'+ finishID).length'來查看該元素是否是'div#hello'的子元素。 – 2013-03-06 15:29:34