I've written an article here.
Basically, what I want to do is select the element before a DIV in a contenteditable area. I'm running into behavior that I do not understand and find myself wondering if this is how "it's supposed to work".
Consider the following markup:
<DIV contenteditable="true">foo<div id="test">bar</div></div>
I want to select the element before <div id="test">
.
So I use:
var sel = document.getSelection();
var range = document.createRange();
var dom_node = document.getElementById( 'test' );
// this is the critical method
range.setStartBefore( dom_node );
range.collapse( true );
sel.removeAllRanges();
sel.addRange( range );
console.log( "selection is :", document.getSelection().getRangeAt(0) );
(Unfortunately, trying this as jsfiddle.net generates some jsfiddle error so I put it up on a static page here)
The range that I am getting is very different between FireFox and Chrome.
Chrome returns a startContainer of a textnode with a startOffset of 3 which nicely points just past the text 'foo'. This is what I would expect. The cursor is moved to that position.
FireFox returns a startContainer of the editable DIV with an offset of 1, pointing to the entirety of the textnode. Not what I would expect. The cursor (if you focus the div), points just to the left of 'bar'.
It becomes stranger if the HTML is changed to:
<DIV contenteditable="true"><div>foo</div><div id="test">bar</div></div>
Repeating the experiment, FireFox returns a startContainer with the editable DIV and a startOffset of 1. The cursor remains before 'bar'. Given the results from the last test, this makes sense to me.
Chrome, however, returns a startContainer with a textnode with length of 0 and nextSibling previousSibling that are both null but a parentNode that is set to the div id=”test”. The cursor remains in front of 'bar'.
Is this the correct behavior? What are you supposed to do when you get a range like this? Or is setStartBefore()/After() just broken?