Is the information in this link accurate?
https://developer.mozilla.org/en-US/docs/DOM/Selection
According to this document:
anchorOffset:
Returns the number of characters that the selection’s anchor is offset within the anchorNode.
Experimentng with FireFox, it seems that definition isn’t always true. Sometimes, the offset properties seem to represent a quantity of childNodes. Based on preliminary tests, the following code works:
var sel = window.getSelection() ;
var points = new Array( 0, 0 ) ;
var offset = new Array( sel.anchorOffset, sel.focusOffset ) ;
var nodes = new Array( sel.anchorNode, sel.focusNode ) ;
if ( isText )
points = offset ;
for ( j = 0 ; j < 2 && ! isText ; j++ ) {
var kids = nodes[j].childNodes ;
for ( var i = 0 ; i < offset[j] ; i++ )
points[j] += kids[i].textContent.length ;
}
First, anyone else have this experience? Second, I’m still experimenting trying to find a reliable method to determine the value of isText.
In some respects, this post is partially a question, partially an answer. Hopefully, comments will reflect new details.
MDN’s definition is wrong [UDPATE: I have corrected MDN now].
anchorOffsetandanchorNode(andfocusNodeandfocusOffset) work just like a Range boundary: the offset is a number of characters within a texty node (text, character data and comment nodes) or the number of child nodes ofanchorNodepreceding the selection anchor in all other node types. In practice, selection boundaries are not always within text nodes, as you’ve observed. An obvious example is when the caret is between two adjacent images (caret represented by a pipe character):Also, Firefox often returns selection boundaries as offsets within elements, especially when a selection selects a whole block element (such as a
<p>). Other browsers don’t tend to do this and prefer to return offsets within text nodes.As for
isText, if I understand you correctly, a full implementation would be something like the following, which is taken from my own code: