I'm trying to prevent the creation of empty text nodes whenever I add
- newlines,
- spaces (including non-breaking spaces)
- tabs
to my HTML structure.
Eg.
<div><div> <!-- Node not created -->
<div>
<!-- Node created -->
<div>
Eg1.
<div><div> <!-- Node not created -->
<div> <div> <!-- Node created -->
Eg2.
<div><div> <!-- Node not created -->
<div> <!-- Node created -->
<div>
<!-- Node created -->
</div>
<div> <!-- Node created -->
Here, for a better undestading:
see what happens into the first <DIV>s -
jsFiddle
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.
and get these results:
to our surprise, there are way more
emptytext 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
emptytext nodes actually containslinebreaks, 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.