2013-03-06 108 views
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> 
+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

回答

7

的問題是:

start = document.getElementById(startID).tagName; 

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

您試圖從tagName,這是一個字符串獲得parentNode。 刪除tagName,你應該沒問題。

+0

Doh!在那裏錯過了那個!謝謝 – 2013-03-06 15:45:46