11

How do I append a element a specific index of the children elements using jQuery append e.g. if I have:

<div class=".container">
   <div class="item"><div>
   <div class="item"><div>
   <div class="item"><div>
   <div class="item"><div>
</div>

and I want to append another item between the second and third item?

ip.
  • 3,306
  • 6
  • 32
  • 42
  • 6
    Presumably `class=".container"` is a typo? It's valid to have `.` in a class name, but not something you'd generally want to do. – bobince May 05 '10 at 21:00

3 Answers3

21

There are a few options:

$("div.container div.item").eq(2).after($('your html'));

$("div.container div.item:nth-child(3)").after($('your html'));

$($("div.container div.item")[2]).after($('your html'));

The same options, but inserting into the same position using "before":

$("div.container div.item").eq(3).before($('your html'));

$("div.container div.item:nth-child(4)").before($('your html'));

$($("div.container div.item")[3]).before($('your html'));
John Fisher
  • 22,355
  • 2
  • 39
  • 64
  • 1
    +1 for `eq()` method instead of the non-CSS-standard (and hence less efficient) `:eq` selector. However, be careful with `:nth-child`; unlike `eq()` and most of the rest of everything, its indices are 1-based (argh). – bobince May 05 '10 at 21:05
  • Men I always forget this. Thanks for the heads up! – user875139 May 15 '15 at 15:54
4

("div.container div.item:eq(1)").after("<element to insert>")

Quasipickle
  • 4,383
  • 1
  • 31
  • 53
-1
$('.container').children()[1].append('whatever');
Prateek
  • 6,785
  • 2
  • 24
  • 37
Fletcher Moore
  • 13,558
  • 11
  • 40
  • 58