How to wrap each word of an element in a span tag?

前端 未结 8 1714
忘掉有多难
忘掉有多难 2020-12-01 07:05
$(\"div.date\")
    .contents()
    .filter(
        function(){
            return this.nodeType != 1; 
        })
    .wrap(\"\");

I

相关标签:
8条回答
  • 2020-12-01 07:44

    Is this what you are trying to achieve?

    <span><div class="date">Dec 22, 2011</div></span>
    

    If so:

    $('div.date').wrap('<span/>');
    

    Or are you trying to get this:

    <span>Dec</span> <span>22,</span> <span>2011</span>
    

    Something like this shoul do the trick:

    var dateInner = $('div.date');
    var wraps = [];
    $.each(dateInner.text().split(' '), function (key, value) {
      wraps.push = '<span>' + value + '</span>';
    });
    
    dateInner.html(wraps.join(''));
    
    0 讨论(0)
  • 2020-12-01 07:44

    Just building on Xeon06 excellent answer.

    I had to do this for a multiple of the same element on the same page.

        $('.element').each(function(){
            var words = $(this).text().split(" ");
            var total = words.length;
            $(this).empty();
            for (index = 0; index < total; index ++){
                $(this).append($("<span /> ").text(words[index]));
            }
        })
    
    0 讨论(0)
提交回复
热议问题