javascript 元素没有方法hasAttribute,为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10819230/
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
Element has no method hasAttribute, Why?
提问by jenswirf
I'm trying to iterate "up" through the DOM nodes from a given element to get the first parent element which has the attribute 'animated'.
我正在尝试从给定元素“向上”遍历 DOM 节点,以获取具有“动画”属性的第一个父元素。
var el = evt.target;
console.log(el);
while (!el.hasAttribute('animated'))
{ el = el.parentNode; }
return el;
console.log(el);
Throws error:
抛出错误:
>>>Uncaught TypeError: Object #<HTMLDocument> has no method 'hasAttribute'
>>>Uncaught TypeError: Object #<HTMLDocument> has no method 'hasAttribute'
How is this possible? I've clearly declared the variable el
and the first log is correct .
这怎么可能?我已经清楚地声明了变量el
并且第一个日志是正确的。
回答by Quentin
The document
object:
该document
对象:
- Is a node
- Is the
parentNode
of the root element (if you were using HTML that would be the<html>
element) - Is not an element.
- 是一个节点
- 是
parentNode
根元素的(如果您使用的是 HTML<html>
元素) - 不是元素。
Only elements have attributes, so only element objects have a hasAttribute
method.
只有元素才有属性,所以只有元素对象才有hasAttribute
方法。
You need to stop testing when you reach the document object (or when you aren't testing an element any longer).
当您到达文档对象时(或不再测试元素时),您需要停止测试。
while (
el.nodeType === 1 &&
(!el.hasAttribute('animated'))
) {
回答by Farhan Ahmad
var el = evt.target
is a document
object and therefore does not have a hasAttribute
attribute.
var el = evt.target
是一个document
对象,因此没有hasAttribute
属性。
回答by jfriend00
You could also make it into a function that returns either null
or the ancestor node that has that attribute:
您还可以将其变成一个函数,该函数返回null
具有该属性的祖先节点:
function findNodeWithAttribute(el, attr) {
while (true) {
if (!el || !el.hasAttribute) {
return null;
} else if (el.hasAttribute(attr)) {
return el;
}
el = el.parentNode;
}
}