It seems that I do not understand the exact action of the DOM method normalize()
.
I thought that it removes entirely empty Text nodes. However I do not observe this effect.
Here is a sample document.
<!DOCTYPE html />
<html lang = "en">
<head>
<meta charset = "Utf-8" />
<title>Normalize</title>
</head>
<body>
<form accept = "#" method = "post">
<fieldset><legend>Using normalize()</legend>
<p>The form is used only to test the method normalize().</p>
<div>
<label for = "text">Label</label>
<input type = "text" name = "text" id = "text"/>
</div>
</fieldset>
</form>
<script>
window.onload = function () {
var element = document.getElementById("text");
do {
alert(element);
element = element.previousSibling;
} while (element.nodeType != Node.ELEMENT_NODE);
alert(element);
var element = document.getElementById("text");
element.parentNode.normalize();
do {
alert(element);
element = element.previousSibling;
} while (element.nodeType != Node.ELEMENT_NODE);
alert(element);
};
</script>
</body>
</html>
The first do-while
outputs nodes when method normalize()
was not yet called.
Its output in IE-11
is the following
[object HTMLInputElement]
[object Text]
[object HTMLLabelElement]
However after calling method normalize()
the next do-while
loop produces the same sequence of outputs:
[object HTMLInputElement]
[object Text]
[object HTMLLabelElement]
I thought that the output
[object Text]
should be absent in the second loop.
What is wrong in my understanding of the method normalize()
?
Or what is the exact definition of the empty Text node in the DOM specification?
'normalize' method definition says 'no text nodes in the sub-tree are empty and there are no adjacent text nodes' In your case there is no text node which is empty, there is on text node which has "↵ " and some spaces. If you change your html to:
<label for = "text">Label</label><input type = "text" name = "text" id = "text"/>
'label' and 'input' element together without spaces, you will not get any alert for '#text' node. Now, if you really wanna see how normalize works, you should create two text nodes with empty values:
document.createTextNode('');
put them in between your 'label' and 'input' element. Then run your code. You will get two alerts for #text node. And after normalization you should not get any alert for #text node.