1

I found this javascript code to highlight selected text, how can i add a function to delete the highlight background (deleting the span that was created) just clicking the highlighted text?

highlight=function()
    {       
    var selection= window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span= document.createElement("span");
    span.style.backgroundColor = "yellow";
    span.appendChild(selectedText);
    selection.insertNode(span);
    }
5
  • 1
    Why did you post the duplicate question? Commented Jan 2, 2012 at 3:36
  • because i dont want change the background to transparent, i wanna delete the span who make the background in my function Commented Jan 2, 2012 at 3:37
  • Why did you accept that answer then? Commented Jan 2, 2012 at 3:38
  • Sorry im new in here, Sergio if you can please help me with my question, thanks Commented Jan 2, 2012 at 3:40
  • See my comments to the original question Commented Jan 2, 2012 at 3:42

1 Answer 1

3
window.highlight = function() {
    var selection = window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span = document.createElement("span");
    span.style.backgroundColor = "yellow";
    span.appendChild(selectedText);
    span.onclick = function (ev) {
        this.parentNode.insertBefore(
            document.createTextNode(this.innerHTML), 
            this
        );
        this.parentNode.removeChild(this);
    }
    selection.insertNode(span);
}

See demo

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.