简体   繁体   中英

HTML / JS - Get selected element class and/or ID

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.

  • 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();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM