Note that there are some explanatory texts on larger screens.

plurals
  1. POSetting the caret position to an empty node inside a contentEditable element
    primarykey
    data
    text
    <p>My task is to set a text caret to appear inside an empty span node within a <code>contentEditable</code> div. </p> <p>The following gives me no problems on Firefox 3.6:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;script type="text/javascript" src="js/jquery-1.4.3.min.js"&gt; &lt;/script&gt; &lt;style&gt; #multiple { border: 1px solid #ccc; width: 800px; min-height: 20px; padding: 5px; outline: none; } &lt;/style&gt; &lt;script&gt; $(document).ready(function(){ var contentEditable = document.getElementById('multiple'); var lastItem = contentEditable.getElementsByTagName('span').item(2); var selectElementText = function(el, win){ win = win || window; var doc = win.document, sel, range; if (win.getSelection &amp;&amp; doc.createRange) { range = doc.createRange(); range.selectNodeContents(el); range.collapse(false); sel = win.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (doc.body.createTextRange) { range = doc.body.createTextRange(); range.moveToElementText(el); range.select(); } } contentEditable.focus(); selectElementText(lastItem); }); &lt;/script&gt; &lt;title&gt;Range Selection Tasks (Make Me Want to Cry)&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="multiple" contentEditable="true"&gt; &lt;span style="color:red"&gt;First&lt;/span&gt;&lt;span style="color:green"&gt;Second&lt;/span&gt;&lt;span style="color:blue"&gt;&lt;/span&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>... but on Webkit and IE, the focus is set to the <em>penultimate</em> span. No idea why. It works if I put a space inside the last span, but then I get a one-character range selection. </p> <p>Having said that, it's acceptable to have whitespace in the last node if the caret is at the very start.</p> <p>Any help with this would be greatly appreciated. Thank you in advance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload