wrap each char in except tags with jQuery
I'm trying to wrap each text character inside a
<div id="test"></div>
with a span tag. No problem there, it's just that I also need to keep nested tags unmodified.
So if the string inside the DIV is:
"Some random text, <b>but</b> wait - there's <a href="http://w3.org">tags</a> inside!"
It should output this for the "but" part
<b><span>b</b><span>u</span><span>t</span></b>
Leaving the < b> and < a> tags alone, but wrapping all other chars in span. I checked text() but that doesn't seem to have a way of preserving tags or "saving back", only extracting the text a开发者_StackOverflow中文版nd permanently removing the < b> and < a>
Maybe some jQuery guru out there knows how to do this?
You can do this by using the following code:
$("div").children().andSelf().contents().each(function(){
if (this.nodeType == 3) {
var $this = $(this);
$this.replaceWith($this.text().replace(/(\w)/g, "<span>$&</span>"));
}
});
See test case on jsFiddle.
精彩评论