How to wrap each word in the gap, but keep the text formatting

How can I wrap every word in a space and keep the text formatting? e.g. br, em, strong

I use the following code to wrap every word from a rich text editor in between, but it removes 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(' '));

        });        
});
+5
source share
1 answer
$('.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(' '));
});        
+6
source

All Articles