DOM Node Types and Operations
In the Document Object Model (DOM), a Node is the fundamental unit that constitutes the document structure. Nodes can be elements, text, comments, attributes, and more. The DOM represents a document as a tree structure, where each node is an element within that tree.
Nodes in the DOM can be categorized into the following types:
- Element Node: Represents an HTML element, such as
<div>,<p>, or<span>. - Text Node: Represents text content within the document, such as "Some text" inside
<p>Some text</p>. - Attribute Node: Represents an attribute of an HTML element, such as the "src" attribute in
<img src="image.png">. - Comment Node: Represents comment content within HTML, such as
<!-- This is a comment -->.
Nodes in the DOM can be accessed and manipulated using JavaScript. For example, the following methods can be used to retrieve nodes:
document.getElementById(): Retrieves a node based on an element's ID attribute.document.querySelector(): Retrieves a node using CSS selectors.parentNode.childNodes[]: Retrieves a list of child nodes for a specified element.parentNode.firstChildandparentNode.lastChild: Retrieve the first and last child nodes of a specified element, respectively.
The following methods can be used to create new nodes:
document.createElement(): Creates a new element node.document.createTextNode(): Creates a new text node.element.setAttribute(): Sets an attribute on an element node.
The following methods can be used to modify nodes:
node.textContent: Modifies the text content of a node.element.setAttribute(): Modifies the attribute value of an element node.parentNode.appendChild(): Adds a node as a child of another node.parentNode.removeChild(): Removes a child node from a parent node.node.cloneNode(): Clones a node.
Through these methods, it is convenient to access, create, modify, and delete nodes in the DOM, enabling dynamic manipulation of web pages.