<script> var is_gecko = /gecko/i.test(navigator.userAgent); var is_ie = /MSIE/.test(navigator.userAgent); function insertNodeAtSelStart() { if(is_gecko) { var S = window.getSelection(); if(!S.isCollapsed) { var R = S.getRangeAt(0); var R1 = R.cloneRange(); var NN = document.createElement('startMarker'); R1.insertNode(NN); NN.parentNode.removeChild(NN); } } if(is_ie) { // IE-specific code } } </script> <div> <span>one two three</span> </div> <input type='button' value='Insert node at selection start' onclick='insertNodeAtSelStart();' />
The first time I click the button after loading the page and selecting some text, Firefox clears the selection. Subsequently, it does not. Is this a bug in my code or in Firefox?
Firefox clears the selection when you disturb it by successfully inserting the Node inside its start point.
For me, a second click sometimes (depending on what range of text is selected) fails with a:
on the insertNode call. Since the insertion is unsuccessful the selection is not cleared. Presumably this is what is happening for you — check your Error Console.
This failure does appear to be a Firefox bug. I can’t quite track down the exact conditions that trigger it, but it is to do with what node boundaries are in the selection.
I can make your example always work (and clear the selection) by calling document.body.normalize() to return the whole span content to a single Text node, after it has been split by the insert/remove cycle.