First word selector

后端 未结 7 682
野性不改
野性不改 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:58
    /*
    URL → https://github.com/melbon/jquery.useWord
    */
    $.fn.lastWord = function() {
      var text = this.text().trim().split(" ");
      var last = text.pop();
      this.html(text.join(" ") + (text.length > 0 ? " <span class='lastWord'>" + last + "</span>" : last));
    };
    
    
    $.fn.firstWord = function() {
      var text = this.text().trim().split(" ");
      var first = text.shift();
      this.html((text.length > 0 ? "<span class='firstWord'>"+ first + "</span> " : first) + text.join(" "));
    };
    
    
    $("#firstWord").firstWord();
    $("#lastWord").lastWord();
    
    0 讨论(0)
提交回复
热议问题