Normalizing Text Nodes

Node.normalize()

It is possible to have adjacent Text nodes in the DOM.  When this occurs their text is displayed next to each other with no space between them.  This can be problematic when traversing the DOM if we are expecting only a single node. To avoid this, the normalize() method can be called on a parent of these text nodes.  When called, normalize() combines adjacent text nodes into a single node.  In addition, if a child is an empty text node, it is removed.

In the example below, the text within the pink box was created by appending three text nodes to the pink box’s node, each with a single character (“t”, “w”, “o”) in it.   We then count the number of text nodes that are children of the pink box’s node and enter the number in the blue box (this code is not shown below).

var container = document.getElementById("container6");
var pinkBox = container.getElementsByClassName("box")[1];

var textNode = document.createTextNode("t");
pinkBox.appendChild(textNode);
textNode = document.createTextNode("w");
pinkBox.appendChild(textNode);
textNode = document.createTextNode("o");
pinkBox.appendChild(textNode);

When the button is pressed, we call normalize on the pink box’s node.

 var container = document.getElementById("container6");
 var pinkBox = container.getElementsByClassName("box")[1];
 pinkBox.normalize();

When the button is pressed we also recount the number of text nodes that are children of the pink box’s node, and update the blue box (also not shown here to keep it simple).