Selection API

The Selection API provides methods to access and manipulate the text or content that the user has selected on a webpage.


Core Components

  • window.getSelection(): Returns a Selection object representing the user's selected text.
  • Range: Represents a part of the document (start and end points).


Example: Get Selected Text

document.addEventListener("mouseup", () => {
    let selection = window.getSelection();
    console.log(selection.toString()); // Logs selected text
});


Example: Modify Selection

You can clear or manipulate selections programmatically.

let selection = window.getSelection();
selection.removeAllRanges(); // Clears the selection

let range = document.createRange();
let p = document.querySelector("p");
range.selectNodeContents(p); // Select the entire paragraph content

selection.addRange(range); // Apply the range as the new selection