Monday, May 20, 2024
38
rated 0 times [  41] [ 3]  / answers: 1 / hits: 24845  / 14 Years ago, mon, november 15, 2010, 12:00:00

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?


More From » textselection

 Answers
72

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)

[#94960] Friday, November 12, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isaacvalentinn

Total Points: 325
Total Questions: 120
Total Answers: 131

Location: North Korea
Member since Tue, Jun 16, 2020
4 Years ago
isaacvalentinn questions
Mon, Jan 18, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Sep 23, 20, 00:00, 4 Years ago
;