Check if “selected text” parent has class

I want to check if currently highlighted/selected text parent has class using JS/jQuery

Ex :

<div class="foo">
    <div> This text is selected with the cursor </div>
</div>

I tried :

if (document.getSelection().parents('.foo').length) {
       console.log("parent has class foo!");
}

But this is obviously not a valid solution since document.getSelection().parents is not a function

Answer

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>