8

I am new to javascript, trying to perform:

document.selection.createRange();

but document.selection always returns undefined.

I am using latest version of chrome.

what am I doing wrong?

thanks!

exexzian
  • 7,782
  • 6
  • 41
  • 52
adi
  • 223
  • 2
  • 4
  • 6

4 Answers4

14

Use window.getSelection(), which is the most cross-browser compatible (it's supported in the current versions of all major browsers) and is the standard. Chrome certainly supports it as fully as other browsers.

document.selection should only be used for IE < 9.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • IE9 doesn't like it : SCRIPT438: Object doesn't support property or method 'getSelection' – Misi May 29 '13 at 14:21
  • 1
    @Misi: In which case your IE 9 must be in one of the compatibility modes. In standards mode, it definitely supports `window.getSelection()`. http://msdn.microsoft.com/en-us/library/ie/ms535873(v=vs.85).aspx#methods – Tim Down May 29 '13 at 14:57
  • function markSelection ( txtObj ) { if ( txtObj.createTextRange ) { txtObj.caretPos = document.selection.createRange().duplicate(); isSelected = true; } How to chage this to document .getselection() – Bhargavi Feb 05 '14 at 12:06
3

Try document.getSelection() or window.getSelection().

Here's a quick example that I tested in chrome

http://jsfiddle.net/hgDwx/

Garett
  • 16,632
  • 5
  • 55
  • 63
  • i've tried using both window.getSelection and Document.getSelection but also the function getRangeAt(index) does not functioning. i've done: var selObj = document.getSelection(); var selRange = selObj.getRangeAt(0); alert(selRange); what do you say? thanks – adi Aug 09 '11 at 22:49
  • im getting rangeCount value always zero – adi Aug 09 '11 at 22:59
  • @adi I've added an example that was test in chrome – Garett Aug 09 '11 at 23:47
  • I assume selection is just the class of the object which is retrieved with document.getSelection() like below: var s = document.getSelection(); s."Any of properties or methods listed in link below"; https://developer.mozilla.org/en-US/docs/Web/API/Selection – Damien Golding Sep 20 '13 at 04:55
2

Browser support for the selection object based on IE11 and Chrome 87.04280.141

Member IE Chrome
document.selection yes no
window.selection no no
document.getSelection() no yes
window.getSelection() no yes

This is the easy part. The problems come when you are trying to use any methods, f.e. getRange() which exists for document.selection (IE compatible), but doesn't exist for document.getSelection(), so for Chrome you need a workaround.

Gefilte Fish
  • 1,600
  • 1
  • 18
  • 17
  • mm... it seems like IE [supports](https://caniuse.com/?search=getSelection) both `window` and `document`'s `getSelection` methods - are you sure about the browser support table? – Oleg Valter is with Ukraine Jun 20 '21 at 07:19
1

Use window.getSelection() instead.

https://developer.mozilla.org/en/DOM/window.getSelection

Jeremy
  • 22,188
  • 4
  • 68
  • 81