Highlight search terms (select only leaf nodes)

前端 未结 7 810
故里飘歌
故里飘歌 2020-11-30 14:20

I would like to highlight search terms on a page, but not mess with any HTML tags. I was thinking of something like:

$(\'.searchResult *\').each(function()          


        
相关标签:
7条回答
  • 2020-11-30 15:14

    I've made a pure JavaScript version of this, and packaged it into a Google Chrome plug-in, which I wish to be helpful to some people. The core function is shown below:

    GitHub Page for In-page Highlighter

    function highlight(term){
        if(!term){
            return false;
        }
    
        //use treeWalker to find all text nodes that match selection
        //supported by Chrome(1.0+)
        //see more at https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker
        var treeWalker = document.createTreeWalker(
            document.body,
            NodeFilter.SHOW_TEXT,
            null,
            false
            );
        var node = null;
        var matches = [];
        while(node = treeWalker.nextNode()){
            if(node.nodeType === 3 && node.data.indexOf(term) !== -1){
                matches.push(node);
            }
        }
    
        //deal with those matched text nodes
        for(var i=0; i<matches.length; i++){
            node = matches[i];
            //empty the parent node
            var parent = node.parentNode;
            if(!parent){
                parent = node;
                parent.nodeValue = '';
            }
            //prevent duplicate highlighting
            else if(parent.className == "highlight"){
                continue;
            }
            else{
                while(parent && parent.firstChild){
                    parent.removeChild(parent.firstChild);
                }
            }
    
            //find every occurance using split function
            var parts = node.data.split(new RegExp('('+term+')'));
            for(var j=0; j<parts.length; j++){
                var part = parts[j];
                //continue if it's empty
                if(!part){
                    continue;
                }
                //create new element node to wrap selection
                else if(part == term){
                    var newNode = document.createElement("span");
                    newNode.className = "highlight";
                    newNode.innerText = part;
                    parent.appendChild(newNode);
                }
                //create new text node to place remaining text
                else{
                    var newTextNode = document.createTextNode(part);
                    parent.appendChild(newTextNode);
                }
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题