You can get the selected text with
window.getSelection();
this has .anchorNode
and .focusNode
properties which contains the (text) node that is selected (depending on what exactly is selected)
See .anchorNode vs .focusNode for the difference.
Giving snippet below. Note, I've used mouseup
just to be able to test selecting without changing the focus/selection. Using mouseup
would already let you know which element was selected. OP didn't include how/when their code was to be run, so this just allows a demonstration of the code.
$(document).on("mouseup", () => {
var parent = $(window.getSelection().focusNode).closest("div");
if (parent.is(".foo"))
console.log("parent has class foo!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="foo">
<p> Select with the mouse </p>
</div>
<div class="notfoo">
<p> Select with the mouse </p>
</div>