I am aware of how to use document.getSelection() to get the string of whatever text the user highlights.
However, how do I access the class and/or id of the element from getSelection()?
Any thoughts?
I am aware of how to use document.getSelection() to get the string of whatever text the user highlights.
However, how do I access the class and/or id of the element from getSelection()?
Any thoughts?
In the object which getSelection() returns you can find the focusNode. focusNode includes the parentNode. Inside that you can find the class and id which you are looking for.
function getSelectionId(){
return getSelection().focusNode.parentNode.id
}
<p id=foo>Select text from this paragraph and then click the button and it should print "foo" which is the id of the paragraph.</p>
<button onclick=console.log(getSelectionId())>Log selection id</button>
I got your problem, Basically, the getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret, You can get the class and id from the getSelection(); But, there are few ways to get class and id value from your HTML page to Javascript.
const anything = document.getElementByClassName("Anything");const anything = document.getElementById("Anything");const selector = document.querySelector(".class #id");const cookies = document.getElementById("id-container") cookies.classList.toggle("active")Follow, this strategy for selecting classNames and id instead of getSelection();