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?
CodePudding user response:
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.
CodePudding user response:
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 cant' 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.
- First one, { For Class }
const anything = document.getElementByClassName("Anything")
; - Second one, { For ID }
const anything = document.getElementById("Anything")
; - Third one, For id and class... It will work on both -
const selector = document.querySelector(".class #id")
; - A quick javascript snippet
const cookies = document.getElementById("id-container") cookies.classList.toggle("active")
Follow, this strategy for selecting classNames and id instead of getSelection();