根据 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 theNode
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, theNode
attributesparentNode
,previousSibling
, andnextSibling
have anull
value forAttr
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 aDocumentFragment
. However, they can be associated withElement
nodes contained within aDocumentFragment
. In short, users and implementors of the DOM need to be aware thatAttr
nodes have some things in common with other objects inheriting theNode
interface, but they also are quite distinct.
正如文本所说,属性节点不被视为元素的子元素,因此它们不包含在 childNodes
中。要获取元素的属性,您可以访问 element.attributes
.
关于javascript - 元素属性是不是节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31362617/