javascript 为什么 parentNode 未定义?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15251294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:03:07  来源:igfitidea点击:

Why is parentNode undefined?

javascriptdom

提问by Mike Sav

I'm trying to write a function that takes an ID then traverses up the DOM to see if that item is a child of a tag. This shouldn't be too hard however my parentNodeis coming back as undefined? What am I missing?

我正在尝试编写一个函数,该函数接受一个 ID,然后遍历 DOM 以查看该项目是否是标签的子项。这应该不会太难但是我parentNode回来了undefined?我错过了什么?

Here's a simplified version of my code... thanks in advance.

这是我的代码的简化版本......提前致谢。

<!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>

回答by Martin Tournoij

The problem is:

问题是:

start = document.getElementById(startID).tagName;

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

You trying to get the parentNodefrom the tagName, which is a string. Remove the tagName, and you should be fine.

你试图让parentNodetagName,这是一个字符串。删除tagName,你应该没问题。