How might I wrap every word in a paragraph with a span while keeping any nested links functioning? Using the code below from here I get close, but splitting on whitespace inserts a span between the a and the href resulting in something like this:
<p><span><a< span> <span>href="#">this</span></a<></span></p>
which obviously renders the link unusable.
$('p').each(function() {
var text = $(this).html().split(/\s+/),//split on space
len = text.length,
result = [];
for( var i = 0; i < len; i++ ) {
result[i] = '<span>' + text[i] + '</span>';
}
$(this).html(result.join(' '));
});
Jsfiddle here which perhaps better illustrates my point. Thanks!
The problem is you don’t want to randomly be inserting
"<span>"tags inside of other tags. A resulting html like:<img <span>src="blahblah"</span>>is going to be an issue, were you ever to get one.You can use a regex to match out the tags in the HTML and only add
<span>tags to everything else. Probably not perfect, but something like:http://jsfiddle.net/5wabK/
It’s probably a little inefficient but I had to use a group at the beginning and the end in order to capture everything before the first tag and after the last one.