admin管理员组

文章数量:1425740

I have this code working, i just want to understand why do i need to use removeAllRanges at the start. Did the sel had a ranges in it automatically when initialized?

function setCaret(boolean_position) {
   var range = document.createRange();
   var sel = window.getSelection();
   range.selectNodeContents($('#board_code')[0]);
   range.collapse(boolean_position);
   sel.removeAllRanges();
   sel.addRange(range);//setting the caret position
} 

I have this code working, i just want to understand why do i need to use removeAllRanges at the start. Did the sel had a ranges in it automatically when initialized?

function setCaret(boolean_position) {
   var range = document.createRange();
   var sel = window.getSelection();
   range.selectNodeContents($('#board_code')[0]);
   range.collapse(boolean_position);
   sel.removeAllRanges();
   sel.addRange(range);//setting the caret position
} 
Share Improve this question edited Jan 28, 2017 at 13:37 Robin 7,9042 gold badges34 silver badges49 bronze badges asked Jun 5, 2013 at 6:48 user2454455user2454455
Add a ment  | 

1 Answer 1

Reset to default 5

Yes, the selection retrieved from window.getSelection() isn't an empty instance like the range created by document.createRange(). Notice the difference in these methods names - one creates new instance and second gets the instance.

The reason is simple - you can have multiple range instances, every containing different positions. But there's only one selection per document.

Therefore, before adding range, usually you have to remove old ranges that are currently selected. Unless, of course, that you want to extend current selection.

Update: As Tim correctly pointed out, only Firefox supports multiple selection ranges. This means that only on Firefox you're able to select more than one piece of DOM at a time - e.g. you can select table's column or add more selections using CTRL key.

Therefore, only Firefox requires that you execute removeAllRanges() before adding next ones. Other browsers will automatically remove old ranges.

本文标签: javascriptWhy use removeAllRAnges() at the start of a selectionStack Overflow