Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert after 2nd element?

How can I insert something after the second form with mform class, for this markup:

<table id="sortme">
  <tr>
    <td>1</td>
    <td><form class="mform"></form></td>
  </tr>
    <tr>
    <td>2</td>
    <td><form class="mform"></form><!---Insert Me here !---></td>
  </tr>
    <tr>
    <td>3</td>
    <td><form class="mform"></form></td>
  </tr>
</table>

To insert after the first form, I can use:

$(function () {
$('<div>block</div>').insertAfter("#sortme form.mform:first");
});

so I've tried this code for the second, didn't work:

$(function () {
$('<div>block</div>').insertAfter("#sortme > form.mform:nth-child(2)");
});
like image 435
rockyraw Avatar asked Mar 04 '26 09:03

rockyraw


2 Answers

Try .insertAfter("#sortme form.mform:eq(1)");

like image 106
Alon Eitan Avatar answered Mar 06 '26 23:03

Alon Eitan


You, also, may use a counter, conditional statement and append as follows:

<script>
    $(document).ready(function(){
      counter = 0;
      $(".mform").each(function(){
        if (counter === 1){
          $(this).append("<div>Block</div>");
        }
        counter++;
      });
    });
  </script>

A demo is HERE

like image 37
SaidbakR Avatar answered Mar 06 '26 21:03

SaidbakR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!