First word selector

后端 未结 7 700
野性不改
野性不改 2020-11-29 06:04

How can I select the first word in a div?

I need to be able to insert a line break after the first word, or wrap it in a span tag. I need to do this for multiple di

7条回答
  •  北海茫月
    2020-11-29 06:39

    Now I now this has already been answered, but I am very new to jquery and thought I would give it a go. Comments please!

    $('div.message').each(function(index) {
        //get the first word
        var firstWord = $(this).text().split(' ')[0];
    
        //wrap it with span
        var replaceWord = "" + firstWord + "";
    
        //create new string with span included
        var newString = $(this).html().replace(firstWord, replaceWord);
    
        //apply to the divs
        $(this).html(newString);
    });
    

提交回复
热议问题