元素没有方法有属性,为什么

Element has no method hasAttribute, Why?

本文关键字:为什么 属性 有方法 元素      更新时间:2023-09-26

我正在尝试从给定元素"向上"遍历 DOM 节点,以获取具有"animated"属性的第一个父元素。

var el = evt.target;
    console.log(el);
while (!el.hasAttribute('animated'))
   { el = el.parentNode; }
return el;
    console.log(el);

抛出错误:

>>>Uncaught TypeError: Object #<HTMLDocument> has no method 'hasAttribute'

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

document对象:

  • 是一个节点
  • 是根元素的parentNode(如果您使用的是 HTML,那将是<html>元素)
  • 不是元素。
只有元素

具有属性,因此只有元素对象具有hasAttribute方法。

当您

到达文档对象时(或者当您不再测试元素时),您需要停止测试。

while (
    el.nodeType === 1 && 
    (!el.hasAttribute('animated'))
) {

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

您还可以将其转换为返回null或具有该属性的祖先节点的函数:

function findNodeWithAttribute(el, attr) {
    while (true) {
        if (!el || !el.hasAttribute) {
            return null;
        } else if (el.hasAttribute(attr)) {
            return el;
        }
        el = el.parentNode;
    }
}