cosmo
cosmo

Reputation: 761

How to detect if selected text is wrapped in span tags

I have a simple contenteditable div that serves an editor, and a button with an onclick function that changes the color of selected text to be yellow.

    function yellow(){
    {       
        var selection = window.getSelection().getRangeAt(0);
        var selectedText = selection.extractContents();
        var span = document.createElement("span");
        span.style.color = "yellow";
        span.appendChild(selectedText);
        selection.insertNode(span);
    }
    }

I recently noticed that if I selected text OUTSIDE of my div, it could still be colored yellow (since I'm using window.getSelection()).

To fix this I added an if statement:

    function yellow(){
    {       
        var selection = window.getSelection().getRangeAt(0);
        if(window.getSelection().baseNode.parentNode.id != "editor1") return;
        var selectedText = selection.extractContents();
        var span = document.createElement("span");
        span.style.color = "yellow";
        span.appendChild(selectedText);
        selection.insertNode(span);
    }
    }

I'm looking to add another if statement similar to this:

if(window.getSelection().baseNode.parentNode.id != "editor1") return;

except instead of id != "editor1", it detects whether the selected text has span text wrapped around it or not.

Upvotes: 1

Views: 1889

Answers (2)

user670839
user670839

Reputation:

Check my answer at https://stackoverflow.com/a/61329546/670839 and just replace A with SPAN. It follows the same logic.

Upvotes: 0

nsmarks
nsmarks

Reputation: 219

if (window.getSelection().baseNode.parentNode.tagName === 'SPAN')

https://developer.mozilla.org/en-US/docs/Web/API/Element/tagName

Upvotes: 2

Related Questions