JavaScript document normalize() Method Tutorial

In this section, we will learn what the document normalize() method is and how to use it in JavaScript.

What is document normalize() Method in JavaScript?

When you use methods like appendChild() to add more than one text node to an element, these text nodes will sit adjacent to each other. This means if you put two text content using the mentioned method, the second text content won’t add to the first one to create a single text node! Instead, you’ll have two text-nodes as the children of an element.

This will produce problems in later times if you decide to style or modify the text content of such elements. For example, now you need to figure out how many text-nodes an element has and every time you want to modify that content, you need to select all the text nodes first and then apply the modification to them.

But if you think about it, having multiple text nodes as the content of an element is not really necessary for most of the times! And for that reason, JavaScript provided a method called normalize() that by applying it on an HTML document, if any of its elements has multiple text nodes all sit next to each other, they’ll become just one single text node in each of these elements.

Essentially, this method creates one text node out of all the text nodes available in elements of an HTML document.

document normalize() Method Syntax:

document.normalize()

document normalize() Method Parameters

The method does not take an argument.

document normalize() Method Return Value

The normalize() method does not return a value.

Example: using document normalize() Method in JavaScript

See the Pen using document normalize() Method in JavaScript by Omid Dehghan (@odchan1) on CodePen.

In this example, if you click on the “Click to create a text node” button, it will add a new text node created by createTextNode() method to the <p> element and the number of child nodes for this element will increase by one.

Now if you click on the “Click to normalize” button, the normalize() method will be executed and all these nodes will join to each other and create only one text node as a result.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies