Highlight a word with jQuery

后端 未结 12 1368
粉色の甜心
粉色の甜心 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:53

    I wrote a very simple function that uses jQuery to iterate the elements wrapping each keyword with a .highlight class.

    function highlight_words(word, element) {
        if(word) {
            var textNodes;
            word = word.replace(/\W/g, '');
            var str = word.split(" ");
            $(str).each(function() {
                var term = this;
                var textNodes = $(element).contents().filter(function() { return this.nodeType === 3 });
                textNodes.each(function() {
                  var content = $(this).text();
                  var regex = new RegExp(term, "gi");
                  content = content.replace(regex, '' + term + '');
                  $(this).replaceWith(content);
                });
            });
        }
    }
    

    More info:

    http://www.hawkee.com/snippet/9854/

提交回复
热议问题