Graham
Graham

Reputation: 8151

What exactly does document.normalize do?

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

What does that mean exactly?

Upvotes: 6

Views: 261

Answers (2)

Quentin
Quentin

Reputation: 943625

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.

Upvotes: 5

deceze
deceze

Reputation: 522165

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.

Upvotes: 6

Related Questions