Setting the caret position to an empty node inside a contentEditable element

Mike picture Mike · Oct 31, 2010 · Viewed 12.1k times · Source

My task is to set a text caret to appear inside an empty span node within a contentEditable div.

The following gives me no problems on Firefox 3.6:

... but on Webkit and IE, the focus is set to the penultimate span. No idea why. It works if I put a space inside the last span, but then I get a one-character range selection.

Having said that, it's acceptable to have whitespace in the last node if the caret is at the very start.

Any help with this would be greatly appreciated. Thank you in advance.

Answer

shay levi picture shay levi · Sep 15, 2013

Set the element's innerHTML to a zero-width character:

('element').innerHTML = '&#200B';

Now the carret can go there.