Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Are you attempting to insert content into an existing element, without disturbing the content that's already in there?</p> <p>The most straightforward answer is <a href="http://dev.w3.org/html5/spec/Overview.html#insertadjacenthtml" rel="noreferrer"><code>insertAdjacentHTML</code></a>. This is an IE scripting extension, since standardised by HTML5:</p> <pre><code>mydiv.insertAdjacentHTML('afterBegin', '&lt;p&gt;Some new stuff&lt;/p&gt;&lt;p&gt;to prepend&lt;/p&gt;'); </code></pre> <p>Unfortunately it is not implemented everywhere. So elsewhere you have to create a new element, set <code>innerHTML</code> on it and then transfer the contents to the target:</p> <pre><code>var container= document.createElement('div'); container.innerHTML= '&lt;p&gt;Some new stuff&lt;/p&gt;&lt;p&gt;to prepend&lt;/p&gt;'; while (container.lastChild) mydiv.insertBefore(container.lastChild, mydiv.firstChild); </code></pre> <p>If you have a lot of new content, this will be slow. You can speed it up on browsers that support DOM Range by making a Range over the new content, extracting it to a DocumentFragment and inserting that fragment into the target node in one go.</p> <p>Unfortunately (again), whether you are using <code>insertAdjacentHTML</code> or <code>innerHTML</code>, there are elements that IE&lt;9 won't set HTML on: most notably <code>&lt;table&gt;</code> and its relations. So in that case you have to surround the HTML in a suitable wrapper for the element name:</p> <pre><code>container.innerHTML= '&lt;table&gt;&lt;tbody&gt;'+newRowsHTML+'&lt;/tbody&gt;&lt;/table&gt;'; </code></pre> <p>and then extract the contents from the inner element to put in the target.</p> <p>The good thing about this is that with tables if you have a lot of new rows you can put them in a single <code>&lt;tbody&gt;</code> and <code>insertBefore</code>/<code>appendChild</code> that body to put all the rows in in one go, which is quicker than one-by-one.</p>
 

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