为什么parentNode未定义?

问题描述:

我试图编写一个函数,它需要一个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> 
+4

尝试'start = document.getElementById(startID);' – alexbusu 2013-03-06 15:27:49

+1

@ AlexanderV.B。 'startID'是一个变量。错误是在哪一行? 'while(start.parentNode)'这里? – 2013-03-06 15:28:23

+0

您可以使用'$('#'+ startID).parent('#'+ finishID).length'来查看该元素是否是'div#hello'的子元素。 – 2013-03-06 15:29:34

的问题是:

start = document.getElementById(startID).tagName; 

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

您试图从tagName,这是一个字符串获得parentNode。 删除tagName,你应该没问题。

+0

Doh!在那里错过了那个!谢谢 – 2013-03-06 15:45:46