How to get the paragraph of selected text in web page with JavaScript?

Sometimes, we want to get the paragraph of selected text in web page with JavaScript.

In this article, we’ll look at how to get the paragraph of selected text in web page with JavaScript.

How to get the paragraph of selected text in web page with JavaScript?

To get the paragraph of selected text in web page with JavaScript, we can use the window.getSelection method.

For instance, we write:

<p>
  hello world
</p>
<button>
  get selection
</button>

to add a p and button elements.

Then we write:

const button = document.querySelector('button')
button.onclick = () => {
  const x = window.getSelection()
  const z = x.anchorNode.parentNode
  console.log(z.innerHTML)
}

to select the button with querySelector.

And then we set button.onclick to a function that gets the selection from the page.

And we get the node with the selected content with x.anchorNode.parentNode.

Finally, we get the innerHTML from the node with the selected text.

Conclusion

To get the paragraph of selected text in web page with JavaScript, we can use the window.getSelection method.