Understanding DOM Nodes
What exactly are DOM nodes? In the Document Object Model, every component within the DOM tree structure is considered a node.
Types of DOM Nodes
- Element nodes: HTML tags such as div, a, p, span, etc.
- Attribute nodes: Properties like class, id, or data attributes
- Text nodes: The actual text content within elemants
Workinng with DOM Nodes
Finding Nodes
To navigate the DOM tree:
// Access parent node
const parent = childElement.parentNode;
// Get child elements (returns a HTMLCollection)
const children = parentElement.children;
// Get previous sibling element
const prevSibling = currentElement.previousElementSibling;
// Get next sibling element
const nextSibling = currentElement.nextElementSibling;
Creating and Adding Nodes
Adding nodes to the DOM involves two steps: creating the node and then inserting it into the DOM tree.
// Create a new element
const newElement = document.createElement('div');
// Append as the last child of parent
parentElement.appendChild(newElement);
// Insert before a specific child
parentElement.insertBefore(newElement, referenceElement);
When elements cannot be found, these methods return null.
Cloning Nodes
For duplicating existing elements, cloning is more efficient than creating from scratch:
// Get the list container
const list = document.querySelector('ul');
// Clone the first list item and append
list.appendChild(list.children[0].cloneNode(true));
The cloneNode() method accepts a boolean parameter: - true: performs a deep clone (including all descendant and text) - false: performs a shallow clone (only the element itself) - Note: The default value is false, so be explicit when needed.
Removing Nodes
To remove an element, it must have a parent node:
This approach is essential for dynamic content management in web applications.