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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:08:49  来源:igfitidea点击:

Element has no method hasAttribute, Why?

javascript

提问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 eland the first log is correct .

这怎么可能?我已经清楚地声明了变量el并且第一个日志是正确的。

回答by Quentin

The documentobject:

document对象:

  • Is a node
  • Is the parentNodeof 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 hasAttributemethod.

只有元素才有属性,所以只有元素对象才有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 documentobject and therefore does not have a hasAttributeattribute.

var el = evt.target 是一个document对象,因此没有hasAttribute属性。

回答by jfriend00

You could also make it into a function that returns either nullor 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;
    }
}