Jaime A Sanchez R
Jaime A Sanchez R

Reputation: 15

this function highlight selected text, how can i delete the span made by javascript clicking the highlighted text?

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);
    }

Upvotes: 1

Views: 1219

Answers (1)

mVChr
mVChr

Reputation: 50195

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

Upvotes: 3

Related Questions