As a function with a little better handling of 0:
function insertAtIndex(i) {
if(i === 0) {
$("#controller").prepend("<div>okay things</div>");
return;
}
$("#controller > div:nth-child(" + (i) + ")").after("<div>great things</div>");
}
EDIT: Added parenthesis in the nth-child selector to avoid NaN errors. @hofnarwillie
function insertAtIndex(i) {
if(i === 0) {
$("#controller").prepend("<div>okay things</div>");
return;
}
$("#controller > div:nth-child(" + (i) + ")").after("<div>great things</div>");
}
window.doInsert = function(){
insertAtIndex(2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="controller">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 4</div>
<div>Item 5</div>
</div>
<button onclick="doInsert()">Insert "great things" at index 2.</button>