Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an element attribute a node or not?

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.

like image 691
alcohol is evil Avatar asked Sep 01 '25 18:09

alcohol is evil


1 Answers

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

From the 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.

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.

like image 69
Felix Kling Avatar answered Sep 04 '25 08:09

Felix Kling