how to modify the document selection in javascript?

I wanna modify the document selection (user currently selected by mouse or keyboard), how to do it in a cross browser way?



I have not worked with text selection enough to provide real help, but what you are trying to do can be done. You will want to look into the following two functions:

  1. createRange() MSDN | MDC
  2. getRangeAt() MDC

I know it can be implemented cross browser. You can see some of it in action here:

By scrolling to the bottom and clicking the Elephant Icon, which uses the Evernote script. However, my script first selects the main content area (you will see it flash orange) and then it deselects once the capture is made.

Here is a mini jQuery plugin that does it. It was adapted by me from some site, and like the comments say, I feel horrible for not remembering. Its really important to note I adapted it to jQuery, but the code came from some site where they explained how to do it:

// Adapted this from somewhere. Feel horrible for not remembering.
$.fn.autoSelect = function(){
    var selectTarget = this[0]; // Select first element from jQuery collection
    if(selectTarget != null) {
         if(selectTarget.tagName == 'TEXTAREA' || (selectTarget.tagName == "INPUT" && selectTarget.type == "text")) {
         } else if(window.getSelection) { // FF, Safari, Opera
             var sel = window.getSelection();
             var range = document.createRange();
         } else { // IE
             var range = document.body.createTextRange();
    return this; // Don't break the chain

It seems this script is a few places online, but here is another variation on it


As an example, and the easiest one, let's say you want to move the user's selection to contain the contents of an element. The following will work in all major browsers:

function selectElementContents(el) {
    var body = document.body, range, sel;
    if (body.createTextRange) {
        range = body.createTextRange();
    } else if (document.createRange && window.getSelection) {
        range = document.createRange();
        sel = window.getSelection();

selectElementContents( document.getElementById("someElement") );


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.