I have the following function to add a span tag with selected text.
function Add() {
var selObj = window.getSelection();
var selRange = selObj.getRangeAt(0);
var newElement = document.createElement("span");
newElement.setAttribute("class", "cls1");
var documentFragment = selRange.extractContents();
newElement.appendChild(documentFragment);
selRange.insertNode(newElement);
selObj.removeAllRanges();
}
It works fine. But I want to prevent adding a new span inside another one.
<a href="#" onclick="Add()">Add Span</a>
<div id="content">
Lorem ipsum dolor sit amet, <span class="cls1">consectetur adipisicing</span> elit,
</div>
If the user selects "adipisicing elit" I don't want to create a new span as "adipisicing" is inside another one. So how can I know whether the selected text includes any part of other span?
Thanks.