Is the element attribute a node or not?
According to http://www.w3schools.com/js/js_htmldom_navigation.asp , element attributes are nodes as well. The example script below only displays the 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>
Result (node):
#text
A
#text
P
#text
SCRIPT
I assume #text is the node name for line breaks etc. (but I don't know why the text after the script is not showing as #text).
Why doesn't it show the attribute href
? Even when I try to see all the child nodes of the anchor element, it only shows the text node inside.
source to share
tl; dr: Yes, they are nodes, but they are handled differently.
From the DOM spec :
Attr
objects inherit an interfaceNode
, but since they are not actually children of the element they describe, the DOM does not consider them part of the document tree. Thus, attributesNode
parentNode
,previousSibling
andnextSibling
have meaningnull
for objectsAttr
. The DOM considers attributes to be properties of elements, rather than separate identification from the elements with which they are associated; this should make it more efficient to implement functionality such as the default attributes associated with all elements of a given type. Also, nodesAttr
cannot be direct childrenDocumentFragment
. However, they can be associated withElement
nodes contained inDocumentFragment
. In short, DOM users and developers should be aware that nodesAttr
have some similarities with other objects that inherit the interfaceNode
, but they are also quite different.
As the text says, attribute nodes are not considered children of the element, so they are not contained in childNodes
. To get the attributes of an element, you can access the . element.attributes
source to share
Element attributes are not nodes.
If you check MDN about.childNodes
(this is a much better source that w3schools has) you will read:
The Node.childNodes read property returns a live collection of the given element's child nodes.
In the DOM3 spec you can read:
Attr objects inherit the Node interface, but since they are not children of the element they describe , the DOM does not consider them part of the document tree.
On another question, why can't you see the text after the tag <script>
because the DOM hasn't been loaded yet. If you put this code at the end, next to </body>
, then everything will be there.
source to share