jquery add not-in-dom element in a ordered stack (in-dom elements)
<p>I have an unexpected problem.</p>

<p><strong>HTML</strong></p>

<pre><code>&lt;div id="div1" class="myDiv"&gt;&lt;/div&gt;
&lt;div id="div2" class="myDiv"&gt;&lt;/div&gt;
&lt;div id="div3" class="myDiv"&gt;&lt;/div&gt;
&lt;div id="div5" class="myDiv"&gt;&lt;/div&gt;
&lt;div id="div6" class="myDiv"&gt;&lt;/div&gt;
</code></pre>

<p><strong>JS</strong></p>

<pre><code>$(function() {
    var $divs = $('.myDiv');
    // create new div not in tree
    var $div = $('&lt;div/&gt;').attr("id","div4").addClass('myDiv');
    // insert #div4 in right position. Only in stack, not in dom tree.
    $divs = $divs.slice(0,3).add($div).add($divs.slice(3));

    console.log($divs);
});
</code></pre>

<p><strong>output</strong></p>

<blockquote>
  <p>[div#div1.myDiv, div#div2.myDiv, div#div3.myDiv, div#div5.myDiv, div#div6.myDiv, <em>div#div4.myDiv</em>]</p>
</blockquote>

<p><strong>Warning: I DON'T want to insert it in dom tree (like <code>$div.appendBefore($divs[3])</code>), I just want append it in my stack <code>$divs</code>.</strong></p>

<p>I thought that this stack was an ordered list. So, my goal was to create on fly a <code>#div4</code> and insert it in <code>$divs</code> stack without insert it in DOM tree. The insert works but it seems that jquery ignore the order given.</p>

<p>I've other solutions for this problem (i.e. append in dom with a display none), ok.. but:</p>

<p><strong>My question is: why?</strong> It's a bug for some cache optimization, or it's a documented feature?</p>

<p>I've also tried:</p>

<pre><code>var $newDivs = $();
$divs.each(function(i,e) {
    if(i==3) 
        $newDivs = $newDivs.add($div);
    $newDivs = $newDivs.add(e);
});
console.log($newDivs);
</code></pre>

<p>but the output is the same.</p>

<p>EDIT: Just for completeness: this was just a fast hack for a complex code. I know that the purpose is not clean </p>
