tags:

views:

126

answers:

4

Hi guys,

For a markup like

<div id="holder">
    <div>div 1</div>
    <div>div 2</div>
    <div>div 3</div>
    <div>div 4</div>
</div>

how do add some markup after the second DIV for instance?

Thanks,
titel

+6  A: 

Try the CSS selector :nth-child():

$("#holder > div:nth-child(2)").after("<div>foobar</div>");

See also the example on the jQuery page of the :nth-child() selector.

Gumbo
A: 

$("#holder div:eq(1)") will select the second child div of the #holder div. (:eq() selector info). Then use the .after() function to append content.

keithjgrant
+1  A: 

Use insertAfter(selector)

http://docs.jquery.com/Manipulation/insertAfter

Aseem Gautam
+2  A: 

use the :eq(index) or :nth-child(index/even/odd/equation) selector in combination with the append(content) or after(content) function.

for example, assuming this code:

<div id="holder">
    <div>div 1</div>
    <div>div 2</div>
    <div>div 3</div>
    <div>div 4</div>
</div>
using append like this
$("#holder>div:eq(1)").append("<div>inserted div</div>");
or this
$("#holder>div:nth-child(2)").append("<div>inserted div</div>");
will give you

<div id="holder">
    <div>div 1</div>
    <div>div 2<div>inserted div</div></div>
    <div>div 3</div>
    <div>div 4</div>
</div>
while using after like this
$("#holder>div:eq(1)").after("<div>inserted div</div>");
or this
$("#holder>div:nth-child(2)").after("<div>inserted div</div>");
will give you

<div id="holder">
    <div>div 1</div>
    <div>div 2</div>
    <div>inserted div</div>
    <div>div 3</div>
    <div>div 4</div>
</div>

using :nth-child can be useful as it enables you to set content every n amount of elements. also, the index of :nth-child starts at 1 while the index of :eq starts at 0

for example, using

$("#holder>div:nth-child(2n)").after("<div>inserted div</div>");
will give you

<div id="holder">
    <div>div 1</div>
    <div>div 2</div>
    <div>inserted div</div>
    <div>div 3</div>
    <div>div 4</div>
    <div>inserted div</div>
</div>

alexanderpas