Working with innerHTML to manipulate text nodes in JavaScript

This article introduces the innerHTML method of JavaScript, this is used for accessing and setting the text nodes in JavaScript. This is very short and beginner level tutorial on the subject.

This is actually going to be a very short tutorial, we are discussing the text node in DOM and its manipulation using the JavaScript. The text node is the leaf node of the DOM tree. It most important part as all the other elements(tags and attributes) are actually there to support the text. This text is the information which is expected to be formatted and rendered by the web browser.

JavaScript provide the support for the text node manipulation in its core. There is a method known as "innerHTML" which helps us to access the text node.

In the following context we are going to demonstrate its use to obtain and set the value of a text node in Javascript. For the demonstration purpose consider the following HTML sample code.

<div id="demodiv">
	Hi! I am a text node.

when we want to access this node first we will need to target the tag element which is parent for this HTML text(in this case the DIV). so we use:

console.log(document.getElementById("demodiv").innerHTML); //access inner html of tag element with id "demodiv"

output on console:

Hi! I am a text node.

similarly we can set the value to change it to something else as shown in following code snippet.

document.getElementById("demodiv").innerHTML = "Hi! I am the new Text Node";

this will result in the change of HTML text displayed on the browser as well as you will see the new text on console output:

Hi! I am the new Text Node

This is quite all about the text node manipulation, isn't this so easy ? Not only the text but you can change overall HTML of the target element using innerHTMl. For example. you can set the content of the "demodiv" to a paragraph element.

document.getElementById("demodiv").innerHTML = "<p>Hi This is a paragraph inside the demodiv</p>";

this will update the "demodiv" DOM and add a new paragraph(<p>) element inside it.