Thursday 29 September 2016

javascript - Is text considered a node too in the DOM?



I started to read about JavaScript and DOM and I found as on this site that in a structure like this:





The title



The body




the text The title and The body are considered nodes too, as represented in the following image (from the same site):



DOM representation



note that The title and The body are represented as children of the actual title respective body nodes. What confuses me is: aren't The title and The body text just values of the nodes </code> and <code><body></code>?</p><br/><br/><br/><p>A similar example I have met on <a href="http://www.w3schools.com/js/js_htmldom_navigation.asp" rel="nofollow noreferrer">http://www.w3schools.com/js/js_htmldom_navigation.asp</a> where in a structure like this:</p><br/><br/><pre><code><html><br/> <head><br/> <title>DOM Tutorial


DOM Lesson one


Hello world!







the values of

and

elements are described like nodes too:




has one child: "DOM Lesson one"



has one child: "Hello world!"





Why are text values inside nodes considered different nodes and not just text values of the nodes which contain them?



Thank you!


Answer




What confuses me is: aren't The title and The body text just values of
the nodes and ?





No, they are actually children of the those nodes. You can see it by outputting children property of a title tag:



document.querySelector('title').children


Text nodes are represented as Node.TEXT_NODE=3 as mentioned here. Only form DOM elements, like input, have value property and the text entered in these inputs is contained there.



Besides text nodes, there are comment nodes, like this:




<!-- DOM Tutorial -->



Why are text values inside nodes considered different nodes and not
just text values of the nodes which contain them?




Possible because they need to represent different structure in memory so that it's possible to manipulate it, for example, change color of a text.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...