Every time you manipulate the DOM, call node.normalize()
to the parent node, it will do the job.
See more at Node.normalize
UPDATED
According to the fiddle you provide, I take a deep look into this issue, I run following code in Chrome 29, based on your html structure.
var i = 0;
function traverse(node){
if (node.firstChild) {
traverse(node.firstChild);
}
if (node.nodeType === 3) {
console.log("text node " + ++i + ": " + node.nodeValue);
if (node.nodeValue !== '') {
console.log("text node " + i + " is not null");
}
if (node.nodeValue.match(/(\r\n|\r|\n)+/g)) {
console.log("nonsense node");
}
}
if (node.nextSibling) {
traverse(node.nextSibling);
}
}
document.addEventListener("DOMContentLoaded", doTraverse);
function doTraverse(){
traverse(document.getElementsByClassName("selector")[0]);
}
and get these results:
text node 1:
text node 1 is not null
nonsense node
text node 2:
text node 2 is not null
nonsense node
text node 3:
text node 3 is not null
nonsense node
text node 4:
text node 4 is not null
nonsense node
text node 5:
text
text node 5 is not null
text node 6: a paragraph
text node 6 is not null
text node 7:
text node 7 is not null
nonsense node
text node 8: a paragraph
text node 8 is not null
text node 9: a paragraph
text node 9 is not null
text node 10:
more text
text node 10 is not null
text node 11:
text node 11 is not null
nonsense node
to our surprise, there are way more empty
text node than we expect. However, if we inspect these elements in Chrome's inspector, everything seems working fine. I guess Chrome optimizes this issue in rendering engine but not in DOM.
We have a clear idea that those empty
text nodes actually contains linebreak
s, which makes your code doesn't work as you expect. So if you do want to remove those text nodes, you can traverse the DOM , find them and remove them(which will be very inefficient and I appreciate better solution).
BTW, in this scenario, node.normalize()
won't work for you since it just remove real empty text node.