Reputation: 37
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
Upvotes: 0
Views: 894
Reputation: 37
Got what I wanted, using a part of @freedomn-n 's solution
$(window.getSelection().focusNode).closest("div").offsetParent().hasClass('foo');
Upvotes: 0
Reputation: 2679
A vanilla JS solution could be:
function checkCSSClass(el, className) {
return el.classList.contains(className);
}
document.addEventListener('mouseup', () => {
const parentEl = document.getSelection().focusNode.parentElement.parentElement;
console.log('has foo class?: ', checkCSSClass(parentEl, 'foo'));
console.log('has bar class?: ', checkCSSClass(parentEl, 'bar'));
});
<div class="foo">
<div>This text is selected with the cursor </div>
</div>
Upvotes: 0
Reputation: 28611
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>
Upvotes: 3