Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery: How do you wrap each letter in a tag?

Tags:

jquery

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.

like image 248
Rob Avatar asked Oct 14 '22 04:10

Rob


1 Answers

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")));
like image 123
Tesserex Avatar answered Oct 18 '22 14:10

Tesserex