How to highlight all text occurrences in a HTML page with JavaScript?

后端 未结 4 1494
逝去的感伤
逝去的感伤 2020-12-09 09:40

I really thought this would have been answered years ago, still I did not find any solution:

I want to highlight (i.e. make a colored background) all occurrences of

4条回答
  •  轮回少年
    2020-12-09 10:24

    If you are trying to highlight the search terms from google then you can use this jquery plugin available at https://github.com/hail2u/jquery.highlight-search-terms

    If you want functionality like chrome. you can use this code.

    $(document).ready(function(){
      var search = ['p', 'div', 'span'];
    
      $("#highlighter").bind('keyup', function(e){
        var pattern = $(this).val();
    
        $.each(search, function(i){
            var str = search[i];        
            var orgText = $(str).text();
    
            orgText = orgText.replace(pattern, function($1){
              return "" + $1 + ""
            });
    
            $(str).html(orgText);
        });    
      });
    });
    

提交回复
热议问题