Set selection range in javascript IE8

I am working on a wysiwyg editor using div [contenteditable = true] and I want to set the selection range from offset X from Node A to offset Y from Node B. I did a good job with Firefox and IE9, code:

var range = document.createRange(); range.setStart(selectNode, 0); range.setEnd(selectNode, selectNode.textContent.length); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); 

But on IE8, the range object is completely different, it does not have setStart / setEnd, and there are no remove / addRange files in the selection object. Please, help,

+6
source share
2 answers

Look at rangy. Its cross browser / API of choice. This is probably what you need.

http://code.google.com/p/rangy/

+4
source

I had a similar problem found in this polyfill, which was very useful for me as I could not use rangy in my situation: http://bl.ocks.org/visnup/3456262

Edit: The original link really ruined. Looking back at my old code, it looks like polyfill never got into the release code, we just went with a function discovery like this:

 if(window.getSelection || document.selection){ 

then on mouseup:

 var range; if(window.getSelection){ var selection = window.getSelection(); range = selection.getRangeAt(0); } else if(document.selection){ range = document.selection.createRange(); if(!range.surroundContents){ // then give up, feature not fully implemented } } // now do stuff with range (ie the selection) 

... and therefore IE8 users are not supported for this feature.

However, all is not lost: there is a newer (than my original answer) polyfill on Github , which can work if you need to support IE8. It looks rather meager and comprehensive.

+3
source

Source: https://habr.com/ru/post/903887/


All Articles