revision:
The normalize() method removes empty text nodes, and joins adjacent text nodes.
document.normalize()
Parameters: none
<script>
function normPara() {
document.normalize();
const body = document.body;
const cc = document.getElementById("cc");
cc.innerHTML = body.childNodes.length;
}
</script>
The normalize() method removes empty text nodes, and joins adjacent text nodes.
node.normalize()
Parameters: none
<script>
function normPara() {
const element = document.getElementById("demo");
element.normalize();
countNodes(element);
}
</script>
The document has 1 child node(s).
<div>
<button onclick="addTextNode()">Add a Text Node</button>
<button onclick="normPara()">Normalize the Document</button>
<p>The document has <span id="cc" style="font-size:1.5vw">1</span> child node(s).</p>
</div>
<script>
function addTextNode() {
const textNode= document.createTextNode("Click again. ");
const body = document.body;
body.appendChild(textNode);
const cc = document.getElementById("cc");
cc.innerHTML = body.childNodes.length;
}
function normPara() {
document.normalize();
const body = document.body;
const cc = document.getElementById("cc");
cc.innerHTML = body.childNodes.length;
}
</script>
Click one buttons to add text to this paragraph, click the other button to normalize the paragraph.
The paragraph above has 1 child node(s).
<div>
<button onclick="addTextNode1()">Add Text</button>
<button onclick="normPara1()">Normalize</button>
<p id="normalize-1">Click one buttons to add text to this paragraph, click the other button to normalize the paragraph.</p><br>
<p>The paragraph above has <b><span id="cd">1</span></b> child node(s).</p>
</div>
<script>
function addTextNode1() {
const node = document.createTextNode(" Click again.");
const element = document.getElementById("normalize-1");
element.appendChild(node);
countNodes(element);
}
function normPara1() {
const element = document.getElementById("normalize-1");
element.normalize();
countNodes(element);
}
function countNodes(element) {
const span = document.getElementById("cd");
span.innerHTML = element.childNodes.length;
}
</script>