Insert HTML into text node with JavaScript

后端 未结 5 1950
萌比男神i
萌比男神i 2020-12-05 13:59

I\'ve got a little text node:

var node

And I want to wrap a span around every occurrence of \"lol\".

node.nodeValue = node.         


        
5条回答
  •  死守一世寂寞
    2020-12-05 14:44

    Not saying this is a better answer, but I'm posting what I did for completeness. In my case I have already looked up or determined the offsets of the text that I needed to highlight in a particular #text node. This also clarifies the steps.

    //node is a #text node, startIndex is the beginning location of the text to highlight, and endIndex is the index of the character just after the text to highlight     
    
    var parentNode = node.parentNode;
    
    // break the node text into 3 parts: part1 - before the selected text, part2- the text to highlight, and part3 - the text after the highlight
    var s = node.nodeValue;
    
    // get the text before the highlight
    var part1 = s.substring(0, startIndex);
    
    // get the text that will be highlighted
    var part2 = s.substring(startIndex, endIndex);
    
    // get the part after the highlight
    var part3 = s.substring(endIndex);
    
    // replace the text node with the new nodes
    var textNode = document.createTextNode(part1);
    parentNode.replaceChild(textNode, node);
    
    // create a span node and add it to the parent immediately after the first text node
    var spanNode = document.createElement("span");
    spanNode.className = "HighlightedText";
    parentNode.insertBefore(spanNode, textNode.nextSibling);
    
    // create a text node for the highlighted text and add it to the span node
    textNode = document.createTextNode(part2);
    spanNode.appendChild(textNode);
    
    // create a text node for the text after the highlight and add it after the span node
    textNode = document.createTextNode(part3);
    parentNode.insertBefore(textNode, spanNode.nextSibling);
    

提交回复
热议问题