I have an HTML structure like this:
<div contenteditable="true">This is some plain, boring content.</div>
I also have this function that allows me to set the caret position to anywhere I want within the div:
// Move caret to a specific point in a DOM element
function SetCaretPosition(object, pos)
{
// Get key data
var el = object.get(0); // Strip inner object from jQuery object
var range = document.createRange();
var sel = window.getSelection();
// Set the range of the DOM element
range.setStart(el.childNodes[0], pos);
range.collapse(true);
// Set the selection point
sel.removeAllRanges();
sel.addRange(range);
}
This code works completely fine until I start adding child tags (span, b, i, u, strike, sup, sub)
to the div e.g.
<div contenteditable="true">
This is some <span class="fancy">plain</span>, boring content.
</div>
Things get more complicated when these child tags end up with child tags of their own e.g.
<div contenteditable="true">
This is some <span class="fancy"><i>plain</i></span>, boring content.
</div>
Essentially, what happens, is that setStart
throws an IndexSizeError
when I try to SetCaretPosition
to an index higher than the start of a child tag. setStart
only works until it reaches the first child tag.
What I need, is for the SetCaretPosition
function to handle an unknown number of these child tags (and potentially an unknown number of nested child tags) so that setting the position works in the same way it would if there were no tags.
So for both this:
<div contenteditable="true">This is some plain, boring content.</div>
and this:
<div contenteditable="true">
This is <u>some</u> <span class="fancy"><i>plain</i></span>, boring content.
</div>
SetCaretPosition(div, 20);
would place the caret before the 'b' in 'boring'.
What is the code I need? Many thanks!