Sometimes, you want to manipulate the user-selected text or element when building web applications. You can go about it in two ways: write code from scratch or use Selection web API.
This web API provides you with the user-selected node so you can perform actions on it. These actions can be anything from hiding the node, expanding it, manipulating it, or deleting it. The node can also be deselected using the API. It is handy when you have to add one-on-one user interaction with the DOM element as they go by selecting it.
Here is a quick demo to get things into perspective:
Here, I have just logged a string on the console, but you can do a lot more with the selected DOM node/s.
The Selection API provides five interfaces; each has a specific purpose:
This interface is used to interact with the selection associated with the document. It tells the developer which part of the document the user has selected.
This method provides you the information about the current selection on the web document level.
This method provides you with information about the Windows level's current selection.
This method is triggered when the selection is changed. It means the user either adds more to the current selection, deselects the current selection, or selects again.
This method executes when the user starts selecting a new DOM element.
The Selection API is supported across all modern web browsers, including Safari, Firefox, Chrome, and Opera.