Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I had a similar problem. Unfortunately none of the solutions worked for me. So I coded it this way:</p> <pre><code>jQuery.fn.insertAt = function(index, element) { var lastIndex = this.children().size(); if (index &lt; 0) { index = Math.max(0, lastIndex + 1 + index); } this.append(element); if (index &lt; lastIndex) { this.children().eq(index).before(this.children().last()); } return this; } </code></pre> <p>Examples for the problem:</p> <pre><code>$("#controller").insertAt(0, "&lt;div&gt;first insert&lt;/div&gt;"); $("#controller").insertAt(-1, "&lt;div&gt;append&lt;/div&gt;"); $("#controller").insertAt(1, "&lt;div&gt;insert at second position&lt;/div&gt;"); </code></pre> <p>Here are some examples taken from my unittests:</p> <pre><code>$("&lt;ul/&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;").insertAt(1, "&lt;li&gt;1&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(-1, "&lt;li&gt;-1&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(-1, "&lt;li&gt;-1&lt;/li&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;").insertAt(-1, "&lt;li&gt;-1&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(-1, "&lt;li&gt;-1&lt;/li&gt;").insertAt(1, "&lt;li&gt;1&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(-1, "&lt;li&gt;-1&lt;/li&gt;").insertAt(99, "&lt;li&gt;99&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;").insertAt(2, "&lt;li&gt;2&lt;/li&gt;").insertAt(1, "&lt;li&gt;1&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;").insertAt(1, "&lt;li&gt;1&lt;/li&gt;").insertAt(-1, "&lt;li&gt;-1&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;").insertAt(1, "&lt;li&gt;1&lt;/li&gt;").insertAt(-2, "&lt;li&gt;-2&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;").insertAt(1, "&lt;li&gt;1&lt;/li&gt;").insertAt(-3, "&lt;li&gt;-3&lt;/li&gt;"); $("&lt;ul/&gt;").insertAt(0, "&lt;li&gt;0&lt;/li&gt;").insertAt(1, "&lt;li&gt;1&lt;/li&gt;").insertAt(-99, "&lt;li&gt;-99&lt;/li&gt;"); </code></pre> <p><strong>Edit:</strong> It handles all negative indizes gracefully now.</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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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