Does chrome supports document.selection?
Asked Answered
S

4

9

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!

Susannasusannah answered 9/8, 2011 at 22:23 Comment(0)
A
15

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.

Aiglet answered 10/8, 2011 at 11:58 Comment(3)
IE9 doesn't like it : SCRIPT438: Object doesn't support property or method 'getSelection'Irrepressible
@Misi: In which case your IE 9 must be in one of the compatibility modes. In standards mode, it definitely supports window.getSelection(). msdn.microsoft.com/en-us/library/ie/…Aiglet
function markSelection ( txtObj ) { if ( txtObj.createTextRange ) { txtObj.caretPos = document.selection.createRange().duplicate(); isSelected = true; } How to chage this to document .getselection()Halford
A
3

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

Here's a quick example that I tested in chrome

http://jsfiddle.net/hgDwx/

Abradant answered 9/8, 2011 at 22:37 Comment(4)
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? thanksSusannasusannah
im getting rangeCount value always zeroSusannasusannah
@Susannasusannah I've added an example that was test in chromeAbradant
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"; developer.mozilla.org/en-US/docs/Web/API/SelectionGisborne
C
3

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.

Casement answered 9/4, 2021 at 11:10 Comment(1)
mm... it seems like IE supports both window and document's getSelection methods - are you sure about the browser support table?Moonrise
L
1

Use window.getSelection() instead.

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

Lapidify answered 9/8, 2011 at 22:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.