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?

1
  • 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. Commented May 5, 2010 at 21:00

3 Answers 3

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')); 
Sign up to request clarification or add additional context in comments.

1 Comment

+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).
4

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

Comments

-1
$('.container').children()[1].append('whatever'); 

2 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.