javascript - 元素属性是不是节点?

标签 javascript html dom

根据 http://www.w3schools.com/js/js_htmldom_navigation.asp tutorial,元素属性也是节点。在下面的示例中,脚本仅显示元素节点。

<!DOCTYPE html>
<html>
<body>

<a href="#">link</a>
<p id="demo"></p>

<script>
var n = document.body.childNodes;
var s = "";
for (var i = 0; i < n.length; i++)
  s += n[i].nodeName + "<br>";
document.getElementById("demo").innerHTML = s;
</script>
some text

</body>
</html>

结果(节点名称)是:

#text
A
#text
P
#text
SCRIPT

我猜 #text 是换行符等的节点名称(但我不知道为什么 SCRIPT 之后的文本不显示为 #text)。

为什么不显示 href 属性?即使当我尝试查看 anchor 元素的所有子节点时,它也只显示内部的文本节点。

最佳答案

tl;dr:是的,它们是节点,但它们的处理方式不同。

来自DOM spec :

Attr objects inherit the Node interface, but since they are not actually child nodes of the element they describe, the DOM does not consider them part of the document tree. Thus, the Node attributes parentNode, previousSibling, and nextSibling have a null value for Attr objects. The DOM takes the view that attributes are properties of elements rather than having a separate identity from the elements they are associated with; this should make it more efficient to implement such features as default attributes associated with all elements of a given type. Furthermore, Attr nodes may not be immediate children of a DocumentFragment. However, they can be associated with Element nodes contained within a DocumentFragment. In short, users and implementors of the DOM need to be aware that Attr nodes have some things in common with other objects inheriting the Node interface, but they also are quite distinct.

正如文本所说,属性节点不被视为元素的子元素,因此它们不包含在 childNodes 中。要获取元素的属性,您可以访问 element.attributes .

关于javascript - 元素属性是不是节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31362617/

相关文章:

javascript - 谷歌地图内容在 window.print() 上不可见

javascript - 使用 jquery 即时设置 js 下拉菜单的样式

javascript - 使用 jquery 更改悬停时的背景颜色

javascript - 我无法将信息添加到 mysql 的表中。我使用 javascript 来显示一条信息消息,但它没有执行任何操作

javascript - 如何在 vanilla javascript 中通过 DOM 创建多个元素?

html - 我的 <a> 标签不起作用?

javascript - 针对多个 ID/元素的 document.getElelementById() 的替代方案

javascript - 如何在vanilla js中点击x次后禁用输入?

javascript - 如何使用 javascript/ajax 将图像 URL 转换为 DOM 文件对象?

javascript - 看似已定义的 JavaScript 变量会引发未定义的错误