1

How can I add new <tr> after a clicked <tr>. On click of this <tr> and remove now created when click other <tr> (with repeat 1st scenario) by jQuery?

I tried like this, but it does not work:

$("#test_table tr").click(function() {
  $(this).prev().remove();
  $(this).closest('tr').append('<tr><td>2.2</td></tr>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="test_table">
  <tr>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
  </tr>
</table>

2
  • api.jquery.com/append insert content to the end of each matched element - so you're inserting a tr into another tr. You need a different insertion method Commented Dec 9, 2021 at 13:56
  • Also note that $(this).closest('tr') will always be $(this) as the event is on the tr and .closest includes itself. Commented Dec 9, 2021 at 14:01

1 Answer 1

1

Given your goal it seems that you want to replace the current tr with the new HTML snippet. To do that you just need to call after() to insert the new HTML, then remove() to clear the original tr:

$("#test_table tr").click(function() {
  $(this).after('<tr><td>2.2</td></tr>').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="test_table">
  <tr>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
  </tr>
</table>

However, as the only effect of this is to change the text within the td, you can just call text() instead:

$("#test_table tr").click(function() {
  $(this).find('td').text('2.2');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="test_table">
  <tr>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
  </tr>
</table>

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.