JSFiddle - React, Tailwind, and code Playground
HTML
<div id="mainDiv" onmouseup="alert(getSelectionContainerElementId())">Select some content here. Here's <b id="bold">some bold text</b></div>
JavaScript
function getSelectionContainerElementId() {
var sel = window.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
var container = range.commonAncestorContainer;
// container could be a text node, so use its parent if so
if (container.nodeType == 3) {
container = container.parentNode;
}
return container.id;
}
return null;
}