First word selector

2020-01-26 07:49发布

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 divs on a page with the same class.

7条回答
祖国的老花朵
2楼-- · 2020-01-26 08:18

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 = "<span class='myClass'>" + firstWord + "</span>";

    //create new string with span included
    var newString = $(this).html().replace(firstWord, replaceWord);

    //apply to the divs
    $(this).html(newString);
});
查看更多
登录 后发表回答