cosmo cosmo - 4 months ago 15
Javascript Question

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.

Answer

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

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