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.

+3


source to share


2 answers


tl; dr: Yes, they are nodes, but they are handled differently.

From the DOM spec :



Attr

objects inherit an interface Node

, but since they are not actually children of the element they describe, the DOM does not consider them part of the document tree. Thus, attributes Node

parentNode

, previousSibling

and nextSibling

have meaning null

for objects Attr

. 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, nodes Attr

cannot be direct children DocumentFragment

. However, they can be associated with Element

nodes contained in DocumentFragment

. In short, DOM users and developers should be aware that nodesAttr

have some similarities with other objects that inherit the interface Node

, 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

+5


source


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.

+2


source







All Articles