javascripttextselection

Can you set and/or change the user’s text selection in JavaScript?


In JavaScript, there are various methods for accessing the user’s text selection, and creating text selections (or ranges) — see http://www.quirksmode.org/dom/range_intro.html.

As per that page, you can programmatically create a range, and access the text within that. But doing this doesn’t change the user’s text selection, or make the user have some selected text if they don’t already.

Can you set and/or change the user’s text selection in JavaScript?


Solution

  • Update 2021

    The Selection API does this. Rather than making a new Selection() (which seemed intuitive, but doesn't work), window.getSelection() always returns a Selection object - even if nothing is highlighted by the user! You can then use setBaseAndExtent() to make a particular node be highlighted - this will change whatever is selected by the user (even if nothing is selected) to match what you specify.

    The example below highlights the question in this StackOverflow page

    const selection = window.getSelection()
    const headerElement = document.querySelector('#question-header a')
    selection.setBaseAndExtent(headerElement,0,headerElement,1)