Is text considered a node too in the DOM?

Question

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

<html>
  <head>
    <title>The title</title>
  </head>
  <body>
     The body
   </body>
</html>

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 <title> and <body>?

A similar example I have met on http://www.w3schools.com/js/js_htmldom_navigation.asp where in a structure like this:

<html>
  <head>
      <title>DOM Tutorial</title>
  </head>
  <body>
      <h1>DOM Lesson one</h1>
      <p>Hello world!</p>
  </body> 
</html>

the values of <h1> and <p> elements are described like nodes too:

<h1> has one child: "DOM Lesson one"

<p> 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!


Show source
| javascript   | dom   | html   2017-01-07 19:01 2 Answers

Answers ( 2 )

  1. 2017-01-07 19:01

    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:

    <title><!-- DOM Tutorial --></title>
    

    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.

  2. 2017-01-07 19:01

    aren't The title and The body text just values of the nodes <title> and <body>?

    Not exactly. They are the values of the text nodes which are children of <title> and <body>, respectively.

    The values themselves are not nodes, but the text nodes are nodes indeed.

    Note not all node types can have values, for example, elements can't. The text can't directly be a value of the element. That's because an element can contain both text and element children, e.g.

    <div>Hello<span> - </span>World</div>
    

    Here it's clear that there is no obvious value for the div element. Instead, you need a tree

    • Element node div with children
      • Text node with value Hello
      • Element node span with children
        • Text node with value -
      • Text node with value World
◀ Go back