Add something after the "n" element using jQuery

Use insertAfter(selector)

.insertAfter()


$("#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.


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>

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.

Tags:

Jquery