I had a similar problem. Unfortunately none of the solutions worked for me. So I coded it this way:
jQuery.fn.insertAt = function(index, element) {
var lastIndex = this.children().size();
if (index < 0) {
index = Math.max(0, lastIndex + 1 + index);
}
this.append(element);
if (index < lastIndex) {
this.children().eq(index).before(this.children().last());
}
return this;
}
Examples for the problem:
$("#controller").insertAt(0, "first insert");
$("#controller").insertAt(-1, "append");
$("#controller").insertAt(1, "insert at second position");
Here are some examples taken from my unittests:
$("
").insertAt(0, "- 0
");
$("
").insertAt(0, "- 0
").insertAt(1, "- 1
");
$("
").insertAt(-1, "- -1
");
$("
").insertAt(-1, "- -1
").insertAt(0, "- 0
");
$("
").insertAt(0, "- 0
").insertAt(-1, "- -1
");
$("
").insertAt(-1, "- -1
").insertAt(1, "- 1
");
$("
").insertAt(-1, "- -1
").insertAt(99, "- 99
");
$("
").insertAt(0, "- 0
").insertAt(2, "- 2
").insertAt(1, "- 1
");
$("
").insertAt(0, "- 0
").insertAt(1, "- 1
").insertAt(-1, "- -1
");
$("
").insertAt(0, "- 0
").insertAt(1, "- 1
").insertAt(-2, "- -2
");
$("
").insertAt(0, "- 0
").insertAt(1, "- 1
").insertAt(-3, "- -3
");
$("
").insertAt(0, "- 0
").insertAt(1, "- 1
").insertAt(-99, "- -99
");
Edit: It handles all negative indizes gracefully now.