What are the types of DOM nodes?
The following users marked this post as Works for me:
|user56529||(no comment)||Apr 27, 2022 at 17:46|
any DOM "tree" node is actually a "branch"
Document Object Model and Nodes
According to the MDN documentation, the DOM (Document Object Model) is "the data representation of the objects that comprise the structure and content of a document on the web."
It's a hierarchical tree-like structure, in which all parts of the document are organized. And by "all parts", I mean: elements, attributes, text, comments, etc. Each of these individual parts is a node.
For example, for this simple HTML:
<div id="main"> <!-- some comment --> <p class="paragraph" style="font-weight: bold">abc<span>def</span></p> </div>
The DOM tree will be like this (the circles are the nodes):
Or, if you prefer ASCII diagrams:
div#main ________________________________|_________________________ | | | | | text <!-- some comment --> text p.paragraph text (line break) (line break) | (line break) | _______________ | | text ("abc") span | text ("def")
Each HTML element is a node. But there are also text nodes (such as "abc" inside the paragraph and "def" inside the
span, and also all the line breaks: one right after the
div opening tag, another one right after the comment, and another one before the closing
Note that the comment is also a node. And the attributes are nodes as well (the
id attribute in the
div, and the
style attributes in the paragraph, are all nodes), although those are not shown in the image above, because "I couldn't find space to fit them" (but they are nodes too).
nodeType property just returns a value that tells the type of the node.
In your code,
e.nodeType == Node.TEXT_NODE is just checking if the node (referenced by variable
e) is a text node. It's just a way to know the node's type (and do whatever you need based on that type).
A common use case is when you're looping through a collection of nodes and wants to do something only if the node is of a specific type (or perform a different action for each type, etc).
You can find all the existing types in the documentation and the DOM Living Standard:
|Node.COMMENT_NODE||8||A Comment node, such as
Note that each type has a numerical value. So
e.nodeType == Node.TEXT_NODE could also be written as
e.nodeType == 3, but using
Node.TEXT_NODE makes the code more clear IMO.
1 comment thread