gpt4 book ai didi

javascript - 为什么我不能像 DOM 标准所说的那样获取节点属性的 nodeType 属性也是一个属性节点?

转载 作者:行者123 更新时间:2023-11-30 13:53:07 24 4
gpt4 key购买 nike

我可以得到 nodeType来自 <a> 这样的节点或 <div>在 Chrome devtools 中,但我无法获得 nodeType的一个属性。我试过这样:

document.getElementByTagName('a')[0].href.nodeType

DOM 标准说属性也是一种节点。为什么不能得到它的nodeType

链接:https://dom.spec.whatwg.org/#attr

最佳答案

...but I can't get the nodeType of an attribute. I've tried like this:

document.getElementByTagName('a')[0].href.nodeType

当您访问元素上的 .href 时,您没有使用属性节点(不是直接),您使用的是属性的反射属性 (它在幕后访问属性节点)。该属性是返回字符串的访问器属性。字符串没有 nodeType 属性。 (您可以在 HTML 规范中找到它,从 the a element 开始,它告诉您它是一个 HTMLAnchorElement ,其中包括 HTMLHyperlinkElementUtils ,其中有 href 定义了 href 访问器的行为属性(property)。)

要直接访问属性节点,您可以使用 attributes收藏或getAttributeNode :

const example = document.getElementsByTagName("a")[0];
const node = example.attributes[0];
console.log(`node.nodeType = ${node.nodeType}`);
console.log(`node.nodeName = ${node.nodeName}`);
console.log(`node.nodeValue = ${node.nodeValue}`);
<a href="http://example.com">example</a>

在您提出的评论中:

But how do you know that?Does the Dom standard says that in any line?

老实说,我在大约 24 年的时间里学习了这些东西,并且不记得我是什么时候第一次了解到虽然属性是 DOM 的一部分,但它们不是节点树的一部分,它们是分开保存的作为 attributes NamedNodeMap。该信息在定义 node tree 的 DOM 规范中。 (注意它没有提到属性节点),但是......你必须寻找它才能捕捉到我认为的。 :-) 不过,如果您对 DOM 和 HTML 规范了解的时间足够长,您就会学会这些东西。

关于javascript - 为什么我不能像 DOM 标准所说的那样获取节点属性的 nodeType 属性也是一个属性节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57840336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com