Javascript window.getSelection() alternative

1.4k views Asked by At

I am trying to select text manually. window.getSelection().getRangeAt(0); line used for window selected text. But I want this pre-selected by me.

foo=function()
    {       
    var selection= "Lorem ipsum dolor"; // Instead of this line window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span= document.createElement("span");
    span.style.backgroundColor = "yellow";
    span.appendChild(selectedText);
    selection.insertNode(span);
    }

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> 
<input type="button" onclick="foo();" value="FOO"/>
1

There are 1 answers

0
axel.michel On

There is the github project findAndReplaceDOMText. A javascript library which might be helpful: It searches for regular expression matches in a given DOM node and replaces or wraps each match with a node or piece of text that you can specify.

You could also use window.find() / createTextRange. This answer shows how to do it. It will match text that crosses element boundaries and does the highlighting for you using document.execCommand().

Finally - if I look at your example and you just want to replace a specific fragment of a text node - you could use a regular expression like this:

element.innerHTML = element.innerHTML.replace(
    /Lorem ipsum dolor/gi,
    '<span class="f">$0</span>'
);