I have spent two days on this, so I will be disheartened if there is a simple answer. I am trying to put a span tag around every letter in a div, while leaving the rest of the tags intact.
<div id="div">
<p>
Of course some of the <strong>text is in other tags</strong> and <strong>some
is in <em>nested tags</em>, etc.</strong>
</p>
</div>
I get very close, but something always trips me up in the end.
I got it! This may not be the optimal solution, but it works! Also note that because of the extra tags, whitespace may get messed up. This also wraps tabs but that's easy to fix too.
function wrap(target) {
var newtarget = $("<div></div>");
nodes = target.contents().clone(); // the clone is critical!
nodes.each(function() {
if (this.nodeType == 3) { // text
var newhtml = "";
var text = this.wholeText; // maybe "textContent" is better?
for (var i=0; i < text.length; i++) {
if (text[i] == ' ') newhtml += " ";
else newhtml += "<span>" + text[i] + "</span>";
}
newtarget.append($(newhtml));
}
else { // recursion FTW!
$(this).html(wrap($(this)));
newtarget.append($(this));
}
});
return newtarget.html();
}
Usage:
$("#div").html(wrap($("#div")));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With