HTML DOM

JS DOM Nodes

Working with DOM Nodes

JavaScript DOM nodes include types and collections for manipulation.

What are DOM Nodes?

DOM nodes are the fundamental building blocks of the Document Object Model (DOM). They represent every single element in an HTML or XML document, allowing developers to access and manipulate the structure, style, and content of web pages programmatically.

In the DOM, everything is a node. Nodes can be elements, attributes, text, comments, and more. Understanding the different types of nodes and their properties is essential for effective DOM manipulation.

Types of DOM Nodes

In the DOM, nodes are categorized into several types, each serving a specific purpose:

  • Element Node: Represents an HTML element, such as <div> or <span>. These are the most common node types developers interact with.
  • Text Node: Represents the text content inside an element. For example, in <p>Hello World</p>, "Hello World" is a text node.
  • Attribute Node: Represents an attribute of an element, like id or class. However, in modern JavaScript, attributes are typically accessed through element properties.
  • Comment Node: Represents comments within the HTML, such as <!-- This is a comment -->.
  • Document Node: Represents the entire document. It is the root of the DOM tree and provides methods to access and create new nodes.

Accessing DOM Nodes

You can access DOM nodes using various JavaScript methods. The most common methods include:

  • document.getElementById(): Finds an element by its ID.
  • document.querySelector(): Returns the first element that matches a specified CSS selector.
  • document.querySelectorAll(): Returns all elements that match a specified CSS selector.

Let's look at an example of accessing and manipulating DOM nodes:

Manipulating DOM Nodes

Once you've accessed DOM nodes, you can manipulate them to change their properties, styles, and content. Here are some common manipulations:

  • Changing Content: Use textContent or innerHTML to update the text or HTML inside an element.
  • Changing Attributes: Use setAttribute() or directly modify properties like id or className.
  • Changing Styles: Modify the style property to change the CSS of an element.

Here's an example of manipulating the style of a DOM node:

Working with Node Collections

When accessing multiple nodes, JavaScript returns a collection of nodes, which can be either a NodeList or an HTMLCollection. These collections are array-like objects that allow you to iterate over nodes, but they are not true arrays.

Here's how you can work with a NodeList:

By understanding and utilizing DOM nodes effectively, you can build dynamic and interactive web applications that respond to user actions and manipulate page content in real-time.