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 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.
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();
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.