Highlight a word with jQuery

后端 未结 12 1525
粉色の甜心
粉色の甜心 2020-11-22 01:20

I basically need to highlight a particular word in a block of text. For example, pretend I wanted to highlight the word "dolor" in this text:



        
12条回答
  •  忘了有多久
    2020-11-22 01:54

    JSFiddle

    Uses .each(), .replace(), .html(). Tested with jQuery 1.11 and 3.2.

    In the above example, reads the 'keyword' to be highlighted and appends span tag with the 'highlight' class. The text 'keyword' is highlighted for all selected classes in the .each().

    HTML

    
       
       

    keyword

    keyword

    keyword

    JS

    $(document).ready(function() {
       var keyWord = $("#lblKeyword").text(); 
       var replaceD = "" + keyWord + "";
       $(".system, .filename, .content").each(function() {
          var text = $(this).text();
          text = text.replace(keyWord, replaceD);
          $(this).html(text);
       });
    });
    

    CSS

    .highlight {
        background-color: yellow;
    }
    

提交回复
热议问题