JS DOM: Node, Node Type, Element
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
DOM 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:
- An HTML element is a node. e.g.
<p>something</p>. - An HTML element text content is a node. e.g. the βsomethingβ in
<p>something</p>. - Doctype is a node.
- HTML Comment is a node.
- Whitespace between tags is a node.
What is Node Type
Each HTML or XML node has a Node Type. Node type is important because typically you want to ignore comment nodes, or Whitespace Nodes, or text nodes.
For example, if you want to get the name of a element, but if the node is a Whitespace Nodes or text node or comment, you'll get error or null.
So, you need to first check the type of the node.
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 value 1.
When working with HTML or XML, most of the time, 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
whitespace nodes.
For example, property
firstChild
return the first child node,
but
firstElementChild
ignores whitespace nodes, return the first element node.
When working with XML, it's more common to work with the more general concept of nodes.
Difference Between Node vs Element
An element is a object represented by HTML tags or XML tags (such as SVG).
A node is more general. Node includes HTML or XML element, but also
- Doctype
- Comment
- text nodes (such as text inside a bold tag)
- Whitespace Nodes
How to get a node
Basic DOM Element Methods
- JS DOM: Node, Node Type, Element
- JS DOM: Get Element by ID, Name, Class etc
- JS DOM: Get Current Script Element
- JS DOM: Get Parent, Child, Sibling
- JS DOM: NodeList vs HTMLCollection
- JS DOM: Iterate HTMLCollection
- JS DOM: Element Attribute Methods
- JS DOM: Class Attribute (get add remove toggle)
- JS DOM: Create Element, Clone
- JS DOM: Insert, Remove, Replace Element
- JS DOM: insert Adjacent Element
- JS DOM: appendChild
- JS DOM: textContent, innerHTML, innerText, nodeValue
- JS DOM: Remove Element
- JS DOM: Remove All Children
- JS DOM: Change Element Content
- JS DOM: Add, Remove Event Handler