DOM Text Content: How to Manipulate Text in Elements

The Document Object Model (DOM) is a tree-like representation of the HTML document that allows us to access and manipulate its elements using JavaScript. Elements are the building blocks of the DOM tree, and they can contain textual content that is displayed on the web page.

In this article, we will learn how to access and modify the text content within elements using JavaScript. We will cover the following topics:

  • Text Nodes: The smallest units of text in the DOM tree that are contained within elements.
  • Text Properties: The properties that allow us to get and set the text content of elements, such as textContent, innerText, and innerHTML.
  • Text Methods: The methods that allow us to create, append, insert, replace, and remove text nodes in the DOM tree, such as createTextNode(), appendData(), insertData(), replaceData(), and removeChild().

Text Nodes

Text nodes are the smallest units of text in the DOM tree that are contained within elements. Text nodes are a type of nodes, which are the basic components of the DOM tree. Nodes can have different types, such as element nodes, attribute nodes, comment nodes, etc. Text nodes are one of the types of nodes that can have child nodes, along with element nodes and document nodes.

Creating text nodes

Text nodes are created automatically when we write text inside an HTML element, such as <p>Hello, world!</p>. The text "Hello, world!" is a text node that is a child of the <p> element node. We can also create text nodes dynamically using JavaScript and the createTextNode() method. This method takes a string argument that specifies the text content of the node and returns a new text node object that can be appended to the DOM tree using methods such as appendChild(), insertBefore(), replaceChild(), etc.

We can access text nodes in the DOM using various methods, such as:

  • childNodes: Returns a collection of all child nodes of a node, including text nodes.
  • firstChild: Returns the first child node of a node, which could be a text node.
  • lastChild: Returns the last child node of a node, which could be a text node.
  • nextSibling: Returns the next sibling node of a node, which could be a text node.
  • previousSibling: Returns the previous sibling node of a node, which could be a text node.

These methods return either a single node or a collection of nodes that are related to the specified node. For example, document.body.firstChild returns the first child node of the document body, which could be a text node, while document.body.childNodes returns a collection of all child nodes of the document body, including text nodes.

Text Properties

Text properties are the properties that allow us to get and set the text content of elements, such as textContent, innerText, and innerHTML. These properties are different from text nodes, which are the actual objects that store the DOM Text Content: How to Manipulate Text in Elements tree. Text properties are convenient ways to access and modify the text content of elements without dealing with text nodes directly.

textContent

The textContent property returns or sets the text content of an element and all its descendants, including text nodes, comment nodes, and CDATA sections. The textContent property does not parse any HTML tags or entities in the text content, and it does not consider the CSS styles or visibility of the element. The textContent property is the standard way to get and set the text content of an element, and it is supported by all modern browsers.

For example, the following code gets and sets the textContent property of a <div> element:

HTML
                        
<div id="container">
  <p>This is a <strong>paragraph</strong>.</p>
  <!-- This is a comment -->
  <script>console.log("This is a script");</script>
</div>
Javascript
                        
// get the textContent property of the div element
let div = document.getElementById("container");
let text = div.textContent;
console.log(text); // This is a paragraph. This is a comment console.log("This is a script");

// set the textContent property of the div element
div.textContent = "This is some new text.";
console.log(div.textContent); // This is some new text.

innerText

The innerText property returns or sets the text content of an element and all its descendants, excluding text nodes in script and style elements. The innerText property parses any HTML tags or entities in the text content, and it considers the CSS styles and visibility of the element. The innerText property is not a standard way to get and set the text content of an element, and it is not supported by all browsers.

For example, the following code gets and sets the innerText property of a <div> element:

HTML
                        
<div id="container">
  <p>This is a <strong>paragraph</strong>.</p>
  <!-- This is a comment -->
  <script>console.log("This is a script");</script>
</div>
Javascript
                        
// get the innerText property of the div element
let div = document.getElementById("container");
let text = div.innerText;
console.log(text); // This is a paragraph.

// set the innerText property of the div element
div.innerText = "This is some new text.";
console.log(div.innerText); // This is some new text.

innerHTML

The innerHTML property returns or sets the HTML content of an element and all its descendants, including text nodes, comment nodes, and element nodes. The innerHTML property does not parse any HTML tags or entities in the text content, and it does not consider the CSS styles or visibility of the element. The innerHTML property is a standard way to get and set the HTML content of an element, and it is supported by all modern browsers.

For example, the following code gets and sets the innerHTML property of a <div> element:

HTML
                        
<div id="container">
  <p>This is a <strong>paragraph</strong>.</p>
  <!-- This is a comment -->
  <script>console.log("This is a script");</script>
</div>
Javascript
                        
// get the innerHTML property of the div element
let div = document.getElementById("container");
let html = div.innerHTML;
console.log(html); // <p>This is a <strong>paragraph</strong>.</p><!-- This is a comment --><script>console.log("This is a script");</script>

// set the innerHTML property of the div element
div.innerHTML = "<p>This is some new <em>HTML</em>.</p>";
console.log(div.innerHTML); // <p>This is some new <em>HTML</em>.</p>

Text Methods

Text methods are the methods that allow us to create, append, insert, replace, and remove text nodes in the DOM tree, such as createTextNode(), appendData(), insertData(), replaceData(), and removeChild(). These methods are different from text properties, which are convenient ways to access and modify the text content of elements without dealing with text nodes directly. Text methods are more low-level and precise ways to manipulate the text nodes in the DOM tree.

createTextNode()

The createTextNode() method creates a new text node with the specified text content and returns it. This method does not append the text node to the DOM tree, but it can be used in combination with other methods, such as appendChild(), insertBefore(), replaceChild(), etc., to insert the text node into the DOM tree.

For example, the following code creates a new text node with the text "Hello, world!" and appends it to the document body:

Javascript
                        
// create a new text node with the text "Hello, world!"
let textNode = document.createTextNode("Hello, world!");
// append the text node to the document body
document.body.appendChild(textNode);

appendData()

The appendData() method appends the specified text to the end of the text content of a text node. This method modifies the existing text node and does not create a new one.

For example, the following code appends the text " How are you?" to the end of the text content of a text node:

Javascript
                        
// get the first text node in the document body
let textNode = document.body.firstChild;
// append the text " How are you?" to the end of the text content of the text node
textNode.appendData(" How are you?");

insertData()

The insertData() method inserts the specified text at the specified offset in the text content of a text node. This method modifies the existing text node and does not create a new one.

For example, the following code inserts the text "fine" at the offset 5 in the text content of a text node:

Javascript
                        
// get the first text node in the document body
let textNode = document.body.firstChild;
// insert the text "fine" at the offset 5 in the text content of the text node
textNode.insertData(5, "fine");

replaceData()

The replaceData() method replaces the specified number of characters starting from the specified offset with the specified text in the text content of a text node. This method modifies the existing text node and does not create a new one.

For example, the following code replaces the 4 characters starting from the offset 5 with the text "good" in the text content of a text node:

Javascript
                        
// get the first text node in the document body
let textNode = document.body.firstChild;
// replace the 4 characters starting from the offset 5 with the text "good" in the text content of the text node
textNode.replaceData(5, 4, "good");

removeChild()

The removeChild() method removes an existing child node from the parent node and returns it. This method can be used to remove text nodes from the DOM tree.

For example, the following code removes the first child node of the document body, which is a text node, and stores it in a variable:

Javascript
                        
// get the first child node of the document body
let textNode = document.body.firstChild;
// remove the text node from the document body and store it in a variable
let removedNode = document.body.removeChild(textNode);

Summary

In this article, we have learned how to access and modify the text content within elements using JavaScript. We have seen that text content is stored in text nodes, which are the smallest units of text in the DOM tree. We have also seen that text content can be accessed and modified using text properties, such as textContent, innerText, and innerHTML, or text methods, such as createTextNode(), appendData(), insertData(), replaceData(), and removeChild().