Get the text of the selection
suggest changeconst sel = document.getSelection();
const text = sel.toString();
console.log(text); // logs what the user selected
document.getSelection() can return null. When a Selection is converted to a string, its toString method supplies the selected text, so a template or concatenation does not need an extra call. console.log on the selection itself prints the object, not that string.
console.log(`${document.getSelection()}`);
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents