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

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

I

8条回答
  •  旧时难觅i
    2020-12-01 07:20

    I needed to give each word a specific id, so, being a newbie, I studied the previously published answers code. Starting from Brad Christie's and Daniel Tonon's code I used .addClass to achieve this result:

        $('.mydiv').each(function(){ 
        var words = $(this).text().split(/\s+/);
        var total = words.length;
        $(this).empty();
        for (index = 0; index < total; index ++){
          $(this).append($(" ").addClass("myclass_" + index).text(words[index]));
          }
        })
    

    which outputs:

        
    bla bla bla

    starting from:

        
    bla bla bla

    It works perfectly for my needs. Maybe some expert programmers could tune up that better!

提交回复
热议问题