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

Viewed 66

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?

2 Answers

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.

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

Related