DOM Nodes
In the DOM, every part of the document is a node, such as elements, attributes, text, comments, and even the document itself. The Node
interface provides methods and properties to work with these nodes.
Key Topics
Types of Nodes
Nodes are categorized into different types based on their role in the DOM. The most common types are:
- Element Node: Represents HTML or XML elements (e.g.,
<div>
). - Text Node: Represents the text inside an element or attribute.
- Comment Node: Represents comments in the document.
- Document Node: Represents the entire document.
Node Properties
Node properties provide information about a node and allow manipulation. Common properties include:
- nodeName: Returns the name of the node (e.g.,
DIV
for a<div>
element). - nodeType: Returns the type of node (e.g., 1 for element nodes, 3 for text nodes).
- nodeValue: Returns or sets the value of a node, primarily for text or comment nodes.
const element = document.getElementById("demo");
console.log("Node Name:", element.nodeName);
console.log("Node Type:", element.nodeType);
Output
> Node Name: DIV
> Node Type: 1
Explanation: The nodeName
property retrieves the name of the node, while nodeType
indicates the type of the node.
Manipulating Nodes
You can dynamically create, clone, or remove nodes using methods like createElement
, cloneNode
, and removeChild
.
const newNode = document.createElement("p");
newNode.textContent = "This is a new paragraph.";
document.body.appendChild(newNode);
const clonedNode = newNode.cloneNode(true);
document.body.appendChild(clonedNode);
document.body.removeChild(newNode);
Output
(A paragraph is added, cloned, and then the original is removed.)
Explanation: The createElement
method creates a new node, cloneNode
duplicates it, and removeChild
removes it from the DOM.
JavaScript Usage in DOM
Below is a complete DOM example demonstrating node creation, manipulation, and removal dynamically.
<!DOCTYPE html>
<html>
<head>
<title>DOM Nodes Example</title>
</head>
<body>
<div id="demo">Original Content</div>
<script>
const newNode = document.createElement("div");
newNode.textContent = "This is a new div.";
document.body.appendChild(newNode);
const clonedNode = newNode.cloneNode(true);
document.body.appendChild(clonedNode);
document.body.removeChild(newNode);
</script>
</body>
</html>
Key Takeaways
- Node Types: Elements, text, and comments are common node types in the DOM.
- Node Properties: Use properties like
nodeName
andnodeType
to understand node characteristics. - Node Manipulation: Create, clone, and remove nodes dynamically using DOM methods.
- Dynamic Content: Node manipulation allows for responsive and interactive web applications.