JQuery: adding an element after the nth element

I need help adding an element to a specific place in the body of the page.

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 in the place where I put the comment above using jQuery. If the page syntax is fixed, is there a way to add an element as the third child of the parent div? I do not want to put placeholders and replace the string.

Thank.

+5
source share
6 answers
$('#div1').children(':eq(1)').after('<button/>');​​​​

JsFiddle example .

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

Insert buttonafter second child # div1

+1
source
function insertAfterNthChild($parent, index, content){
    $(content).insertAfter($parent.children().eq(index));
}

// Usage:
insertAfterNthChild($('#div1'), 1, '<button>Click me!</button');
+1

jQuery nth-child() .

$("input:nth-child(1)").after( "<your html here>" );
0

.. ,

//                  v--- Change n to insert at different position
$('#div1 :nth-child(2)').after('<button>Test</button>');

DEMO: http://jsfiddle.net/m5Gyz/

0

use: http://api.jquery.com/nth-child-selector/

   $("input:nth-child(1)").after('<input type="button" value="button"/>');

: http://jsfiddle.net/epinapala/JB4fr/1/

0
source

All Articles