3

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)");
});

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, your first suggestion worked, second one doesn't though, what's the difference?
@rockyraw - The one I've deleted won't work, just realized that
1

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

1 Comment

FYI - You can also get the current index by passing it to the .each() callback function ($(".mform").each(function(index){) - and check if( index === 1)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.