I'm working on a wysiwyg editor using div[contenteditable=true] and I want to set a selection range from offset X of Node A to offset Y of Node B. I did it well on Firefox and IE9, the code is :
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 totally different, it has no setStart/setEnd, and the selection object has no remove/addRange stuffs. Please help,
I'm working on a wysiwyg editor using div[contenteditable=true] and I want to set a selection range from offset X of Node A to offset Y of Node B. I did it well on Firefox and IE9, the code is :
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 totally different, it has no setStart/setEnd, and the selection object has no remove/addRange stuffs. Please help,
Share Improve this question edited Jun 12, 2021 at 0:55 d4nyll 12.7k6 gold badges57 silver badges70 bronze badges asked Dec 16, 2011 at 4:20 camapconcamapcon 611 silver badge2 bronze badges2 Answers
Reset to default 4Take a look at rangy. Its a cross browser range/selection API. That's probably what you need.
http://code.google./p/rangy/
I had a similar problem found this polyfill which was quite useful to me, as I could not use rangy in my situation: http://bl.ocks/visnup/3456262
Edit: original link has indeed gone dead. Looking back over my old code it looks like the polyfill never made it into the release code, we simply went with feature detection as follows:
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 (i.e. the selection)
...and the IE8 users are therefore not supported for that feature.
However all is not lost: there's a newer (than my original answer) polyfill on Github which might work if you have to support IE8. It looks both pretty lean and prehensive.