According to http://www.w3schools.com/js/js_htmldom_navigation.asp tutorial, element attributes are also nodes. In the example below, script is showing only element nodes.
<!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>
The result (node names) is:
#text
A
#text
P
#text
SCRIPT
I guess #text is node name for line breaks etc (but I have no idea why text after SCRIPT is not shown as #text).
Why it's not showing href
attribute? Even when I try to see all child nodes of anchor element, it's showing only text node inside.
tl;dr: Yes, they are nodes, but they are treated differently.
From the 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.
As the text says, attribute nodes are not considered to be children of the element, hence they are not contained in childNodes
. To get the attributes of an element, you can access element.attributes
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With