To do this, there is a DOM method: normalize() (see also MDC ). You need to call it on the ancestor of the text nodes that you want to normalize, for example, their parent. normalize() works in the entire subtree of the node for which it is being called, so you can call it outside of the each() loop.
$this[0].normalize();
However, this method causes the entire browser to crash in some cases in IE 6 and, possibly, in later versions of IE. You may need to write your own. Here is my implementation:
function normalize(node) { var child = node.firstChild, nextChild; while (child) { if (child.nodeType == 3) { while ((nextChild = child.nextSibling) && nextChild.nodeType == 3) { child.appendData(nextChild.data); node.removeChild(nextChild); } } else { normalize(child); } child = child.nextSibling; } }
source share