Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly does document.normalize do?

Tags:

javascript

I read that document.normalize Removes empty Text nodes, and joins adjacent nodes.

What does that mean exactly?

like image 608
Graham Avatar asked Aug 16 '16 13:08

Graham


2 Answers

A Text node would be this:

<p>
  <span>foo</span>
  bar
</p>

<p> is a node, <span> is a node, so what is "bar"? → It's a text node.

Using the DOM API, it's possible to create empty text, or two adjacent text nodes:

var wrapper = document.createElement("div");

wrapper.appendChild(document.createTextNode("Part 1"));
wrapper.appendChild(document.createTextNode("Part 2"));

In HTML that would just be <div>Part 1Part2</div>, but to the DOM it's two separate text nodes, which is… weird.

Node.normalize normalises this to get rid of such inefficient anomalies; it would merge both text nodes into one, and remove text nodes which are entirely empty.

like image 169
deceze Avatar answered Nov 06 '22 14:11

deceze


Given:

p element
   text node containing ""
p element
   text node containing "Hello, "
   text node containing "world"

It will convert it to

p element
p element
   text node containing "Hello, world"

The text node inside the paragraph by itself, with no content, is removed entirely.

The two adjacent text nodes are joined together into a single text node with the combined text.

like image 37
Quentin Avatar answered Nov 06 '22 13:11

Quentin