JS DOM: Node, Node Type
When writing JavaScript code to manipulate HTML, it's critical to understand the concept of node, element, whitespace node, text node.
What is a node
HTML is a tree structure. Think of it as nested boxes. Start with one big box. Inside that box, there are many smaller boxes. Inside each, may be even smaller boxes. Repeat. Each of the box, is called a node.
Example of nodes
<!-- Doctype is a node. --> <!DOCTYPE html> <!-- this is a node. html comment is a node. --> <!-- An HTML element is a node. --> <p>something</p>. <!-- An element's text content is a node. The “ abc” here. --> <p><b>some</b> abc</p> <!-- text between tags is also a node. the abc here with newline before and after. --> <div>dog</div> abc <div>cat</div> <!-- Whitespace between tags is a node. --> <div>dog</div> <div>cat</div>
What is node type
Node type is a integer that indicates the type of the node. For example, is it an html element or text node or comment node etc.
What is an element
- An element is a special type of node, that is represented by a tag in HTML or XML source code.
- Elements are Node Type of value 1.
When working with HTML or XML, often you want to work with elements, not nodes such as Whitespace Nodes or comment nodes.
Many DOM interfaces have a version that return only elements and ignore
text nodes (including whitespace nodes).
For example, property
firstChild
return the first child node of any type,
but
firstElementChild
return the first element node.