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
Why is parentNode undefined?
提问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 parentNode
is 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 parentNode
from the tagName
, which is a string.
Remove the tagName
, and you should be fine.
你试图让parentNode
从tagName
,这是一个字符串。删除tagName
,你应该没问题。