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:

  1. Element Node: Represents an HTML element, such as <div>, <p>, or <span>.
  2. Text Node: Represents text content within the document, such as "Some text" inside <p>Some text</p>.
  3. Attribute Node: Represents an attribute of an HTML element, such as the "src" attribute in <img src="image.png">.
  4. 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:

  1. document.getElementById(): Retrieves a node based on an element's ID attribute.
  2. document.querySelector(): Retrieves a node using CSS selectors.
  3. parentNode.childNodes[]: Retrieves a list of child nodes for a specified element.
  4. parentNode.firstChild and parentNode.lastChild: Retrieve the first and last child nodes of a specified element, respectively.

The following methods can be used to create new nodes:

  1. document.createElement(): Creates a new element node.
  2. document.createTextNode(): Creates a new text node.
  3. element.setAttribute(): Sets an attribute on an element node.

The following methods can be used to modify nodes:

  1. node.textContent: Modifies the text content of a node.
  2. element.setAttribute(): Modifies the attribute value of an element node.
  3. parentNode.appendChild(): Adds a node as a child of another node.
  4. parentNode.removeChild(): Removes a child node from a parent node.
  5. 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.