JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" onmousedown="alert(elementContainsSelection(document.getElementById('cake')))" value="Selection contained in 'slice of cake'?">
<div contenteditable="true">
Cup of tea and a <b id="cake">slice of cake</b>
</div>
JavaScript
function isOrContains(node, container) {
while (node) {
if (node === container) {
return true;
}
node = node.parentNode;
}
return false;
}
function elementContainsSelection(el) {
var sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount > 0) {
for (var i = 0; i < sel.rangeCount; ++i) {
if (!isOrContains(sel.getRangeAt(i).commonAncestorContainer, el)) {
return false;
}
}
return true;
}
} else if ( (sel = document.selection) && sel.type != "Control") {
return isOrContains(sel.createRange().parentElement(), el);
}
return false;
}