2013-03-06 3 views
3

ID를 가져 와서 해당 항목이 태그의 하위인지 확인하기 위해 DOM을 탐색하는 함수를 작성하려고합니다. 그러나 내 parentNodeundefined으로 다시 돌아오고 있습니다. 내가 뭘 놓치고 있니?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

+1

@ AlexanderV.B를 사용해보십시오. 'startID'는 변수입니다. 어떤 라인에 오류가 있습니까? 'while (start.parentNode)'여기에? –

+0

'$ ('#'+ startID) .parent ('#'+ finishID) .length'를 사용하면'div # hello'의 자식인지 알 수 있습니다. –

답변

7

문제는 :

start = document.getElementById(startID).tagName; 

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

당신은 문자열을 인 tagName,에서 parentNode을 시도. tagName을 제거하면 문제가 없습니다.

+0

Doh! 그 하나를 놓쳤다! 감사 –

관련 문제