Sometimes, we want to get the parent element of a selected text with JavaScript.
In this article, we’ll look at how to get the parent element of a selected text with JavaScript.
How to get the parent element of a selected text with JavaScript?
To get the parent element of a selected text with JavaScript, we can use the getSelection
method.
For instance, we write:
<button>
get selection
</button>
<div>
<section>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</section>
</div>
to add a button and some text.
Then we write:
const button = document.querySelector('button')
button.onclick = () => {
console.log(window.getSelection().anchorNode.parentElement)
}
to select the button with querySelector
.
And then we set the button.onclick
property to a function that gets the selection with window.getSelection
.
Then we use the anchorNode.parentElement
property from the returned object to get the parent node of the selected text.
Conclusion
To get the parent element of a selected text with JavaScript, we can use the getSelection
method.