title: Set caret position in contenteditable div
body: <h2>Intro</h2>
  
  <p>When editing the content of a contenteditable DOM Object, different browsers have different behaviours. For instance, Firefox 18.0 creates a new paragraph (<code>&lt;p&gt;</code>) or a line break <code>&lt;br/&gt;</code> in some instances while Chrome 24 creates a <code>&lt;div&gt;</code>.</p>
  
  <p>In order to cope with this, I'm listening to the <code>DOMNodeInserted</code> event and replacing the new inserted nodes with p tags.</p>
  
  <hr>
  
  <h2>Problem</h2>
  
  <p>The problem is placing the caret in place. <strong>I've read tons of posts in SO regarding this same subject but none of the provided answers have worked</strong>, at least in Chrome 24.</p>
  
  <hr>
  
  <h2>Code</h2>
  
  <p><a href="http://jsfiddle.net/tivie/kmkcJ/" rel="nofollow"><strong>JSFiddle</strong></a></p>
  
  <pre><code>obj.addEventListener("DOMNodeInserted", onNodeInsert, false);
  
  function onNodeInsert(e) {
      var range    = document.createRange(),
          sel      = window.getSelection(),
          newNode  = e.target,
          tagName  = newNode.tagName.toLowerCase(),
          lnbrNode = document.createElement('br'),
          pNode    = document.createElement('p');
  
      if (tagName === 'div' &amp;&amp; newNode.getAttribute("id") === null) {
          // First we remove the event listener so that it doesn't get triggered again
          this.removeEventListener('DOMNodeInserted', onNodeInsert, false);
  
          // Creates a p node and removes the div
          newNode.parentNode.replaceChild(pNode, newNode);
          pNode.appendChild(lnbrNode);
  
          // Places the caret where it belongs
          range.setStart(pNode, 0);
          sel.removeAllRanges();
          sel.addRange(range);    
  
          //We can restore the event listener now
          this.addEventListener("DOMNodeInserted", onNodeInsert, false);
      }
  }
  </code></pre>