To extend the TJ response to better meet the OP requirement, the provided function cannot be called in a loop (iterates through nodes).
Personally, I had to convert all the direct text nodes into gaps similar to the OPs planned (by reference nodeType==3 ).
The problem is that when converting nodes inside a loop, it discards the index! . Here is a finely tuned code that converts all text nodes into wrapped nodes (optimized):
for(var txtnodes=[],nodes=XXXX.childNodes,i=0,j=nodes.length;i<j;i++) { if(nodes[i].nodeType==3) txtnodes[txtnodes.length] = nodes[i]; } for(var m=0,n=txtnodes.length;m<n;m++) { var span = document.createElement('span'); pg.insertBefore(span,txtnodes[m]); span.appendChild(txtnodes[m]); }
This function effectively "saves them later" and converts them after the fact. Variable declarations are all compressed and inline, and all loops are optimized for long node trees.
There are no other articles on this topic on Google, so happy coding for any future adventurers.
source share