Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Adding element after nth element

Tags:

jquery

I need help in adding an element at a particular location in the page body.

Here is my page code.

<div id="div1>
  <label id="label1"></label>
  <input type="text1"></input>
  <!-- Insert button here -->
  <span id="span1"></span>
</div>

I want to add a button at the location where I have put a comment above using jQuery. If the page syntax is fixed, is there a way I can add an element as a third child of the parent div? I do not want to put placeholders and do a string replace.

Thanks.

like image 448
Sreejith K. Avatar asked Jun 25 '12 19:06

Sreejith K.


2 Answers

$('#div1').children(':eq(1)').after('<button/>');​​​​

jsFiddle example.

like image 64
j08691 Avatar answered Sep 18 '22 14:09

j08691


button.insertAfter($('#div1').children().eq(1));

This will insert the button after the 2nd child of #div1

like image 38
jackwanders Avatar answered Sep 17 '22 14:09

jackwanders