为什么parentNode未定义?

Mik*_*Sav 3 javascript dom

我正在尝试编写一个带有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>
Run Code Online (Sandbox Code Playgroud)

Mar*_*oij 7

问题是:

start = document.getElementById(startID).tagName;

    while (start.parentNode) {
        start = start.parentNode;
Run Code Online (Sandbox Code Playgroud)

你试图让parentNodetagName,这是一个字符串.删除tagName,你应该没事.