tags:

views:

49

answers:

3

Say I have this:

<div id="controller">
 <div id="first">1</div>
 <div id="second>2</div>
</div>

but say I wanted to insert a new div arbitrarily based on an index I supply.

Say I gave the index to insert of 0, the result should be:

<div id="controller">
  <div id="new">new</div>
  <div id="first">1</div>
  <div id="second">2</div>
</div>

and if I have an index to insert of 2 the result would be.

<div id="controller">
  <div id="first">1</div>
  <div id="second">2</div>
  <div id="new">new</div>
</div>

and if I give an index of 1 the result would be:

<div id="controller">
  <div id="first">1</div>
  <div id="new">new</div>
  <div id="second">2</div>
</div>

just forget that last example's format. The simple act of copying and pasting HTML code on this site is horrific enough to make me about scream and pull my hair out and I dont want to spend anymore time messing with it!

A: 

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 + ")").before("<div>great things</div>");   
}
Andy Gaskell
You might wanna use [`.before()`](http://api.jquery.com/before/), instead of [`.append()`](http://api.jquery.com/append/) ;)
Reigel
Fixed - thanks.
Andy Gaskell
A: 

You could always use prepend('#div');

ex.

$(document).ready(function(){

$('#first').prepend('<div id="new">New</div>');

});​

That would put "#new" before "#first" Not sure if that's what you want.

MoDFoX
That takes care of the 0th case. What about the 2nd position? He wants to be able to specify by number where to insert the div in the list o' divs
Tommy
A: 

If you need to do this a lot, you can wrap it in a little function:

​var addit = function(n){
  $('#controller').append('<div id="temp">AAA</div>')
    .stop()
    .children('div:eq('+n+')')
    .before( $('#temp') );
} 

addit(2); // adds a new div at position 2 (zero-indexed)
addit(10); // new div always last if n greater than number of divs
addit(0); // new div is the only div if there are no child divs

If you're concerned about that temporary ID, you can add a final step to remove it.

Edit: Updated to handle cases of zero children, and specified n > current number of divs.

Ken Redler
the problem would be if the `$('#controller')` doesn't have any children, then this function would not work... `addit(0)`
Reigel
Reigel, that's true. For fun, I really wanted to try to avoid any (native) conditional. This updated one seems to work for the border cases.
Ken Redler