In this section, we will learn what the Element normalize() method is and how to use it in JavaScript.
What is Element 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 element, if it has multiple text nodes all sit next to each other, they’ll become just one single text node.
Essentially, this method creates one text node out of all the text nodes available in an element.
JavaScript normalize() Method Syntax:
element.normalize();
JavaScript normalize() Method Parameter
The method does not take an argument.
JavaScript normalize() Method Return Value
The method does not return a value.
Example: using normalize() method in JavaScript
See the Pen using normalize() method in JavaScript by Omid Dehghan (@odchan1) on CodePen.