1
2
3<...">

How to add an element after the first child div in jquery?

Assuming I have the following divs:

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

How can I in jquery or javascript make it so that I can add an element immediately after the first child of mydiv. Or is there some kind of selector that allows me to select and add after the first child?

 <div> <div>1</div> <div>Place to Insert Subsequent div</div> <div>2</div> <div>3</div> <div>4</div> </div> 
+7
source share
3 answers

You can do this using :first-child and after :

 $("#mydiv div:first-child").after(newDiv); 

Demo

+25
source

I prefer using eq() instead of first-child , because it is more flexible, if I ever wanted to change it after the 2nd or 3rd div, I can just change the value 0 in eq(0) to eq(1) or eq(2) .

  $("#mydiv div:eq(0)").after('<div>Place to Insert Subsequent div</div>') 

http://jsfiddle.net/KjY7H/

+11
source

To maintain readability, you can save the div you want to add to the variable:

 var subsequentDiv = $('<div>Place to Insert Subsequent div</div>'); 


Then, using your variable, use your preferred jQuery method, in my example I use "insertAfter":

 subsequentDiv.insertAfter('#mydiv div:eq(0)'); // selects children by its index, the first div is equal to 0 subsequentDiv.insertAfter('#mydiv div:lt(1)'); // selects children that its index is lower than 1 (it means the second div) 


Another way to achieve the same result is to read the contents of the div using the "contains filter":

 subsequentDiv.insertAfter('#mydiv div:contains("1")'); 

http://jsfiddle.net/cadence96/tyBnX/1/

0
source

All Articles