views:

168

answers:

4

Hi

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?

+2  A: 

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

Pickle
A: 

$(".container").children()[1].append("watever");

Fletcher Moore
this will not work since [1] returns the native DOM object which does not know about a function 'append()'
jAndy
I should avoid jQuery questions.
Fletcher Moore
+3  A: 

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
+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
A: 
$('.container').find('div').eq(1).after("<div class='item'></div>");

will add a new div after the second div.item for instance.

Kind Regards

--Andy

jAndy