JV10
JV10

Reputation: 891

How to wrap each word in a span but retain text formatting

How can I wrap each word in a span and retain text formatting? e.g. br, em, strong

I'm using the following code to wrap each word from a rich text editor in a span, but it's stripping out all my formatting.

$(window).load(function() {
$(".hero_image p").addClass("hero_image_caption");
$('.hero_image p').each(function(){
    var text = $(this).text().split(' ');

    for( var i = 0, len = text.length; i < len; i++ ) {
        text[i] = '<span>' + text[i] + '</span>';
        }
        $(this).html(text.join(' '));

        });        
});

Upvotes: 5

Views: 5333

Answers (1)

user1348010
user1348010

Reputation:

$('.hero_image p').each(function(){
    var text = $(this).html().split(' '),
        len = text.length,
        result = []; 

    for( var i = 0; i < len; i++ ) {
        result[i] = '<span>' + text[i] + '</span>';
    }
    $(this).html(result.join(' '));
});        

Upvotes: 6

Related Questions