: How to highlight certain words with jQuery

前端 未结 2 1708
醉酒成梦
醉酒成梦 2020-12-22 04:20

I\'m looking for a script than can highlight a certain number of words depending on their position. example, for the following contentI want to highlight only the second, th

相关标签:
2条回答
  • 2020-12-22 04:33

    This jQuery plugin is what you're looking for:

    • jQuery Highlight

    It does exactly what you want, traverses the DOM TextNodes and looks for the text to search, when it find one occurrence it creates an span element.

    Usage :

    $('p').highlight('bibendum sem ut'); 
    
    0 讨论(0)
  • 2020-12-22 04:48

    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, '<span class="highlight">' + term + '</span>');
                  $(this).replaceWith(content);
                });
            });
        }
    }
    

    More info:

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

    0 讨论(0)
提交回复
热议问题