CoderInside CoderInside - 1 month ago 18
jQuery Question

How find the next table tbody jquery

I'm trying to find the table next to the Clicked Button.
All tables and Buttons are Dynamically created.

<button type="button" onclick="addRows(this)">Add Row</button>
<table>
<tbody>
<td>A</td>
<td>A</td>
</tbody>
</table>
<button type="button" onclick="addRows(this)">Add Row</button>
<table>
<tbody>
<td>B</td>
<td>B</td>
</tbody>
</table>
<button type="button" onclick="addRows(this)">Add Row</button>
<table>
<tbody>
<td>C</td>
<td>C</td>
</tbody>
</table>
<button type="button" onclick="addRows(this)">Add Row</button>
<table>
<tbody>
<td>A</td>
<td>A</td>
</tbody>
</table>


I'm using this but I can get the next table to the Button:

$(this).closest("table").find("tbody");

Answer

You need to use .next() to get the next element.

$(this).next("table").find("tbody")

.closest() is for finding the closest containing element, not an adjacent element. Since the button isn't inside a table, $(this).closest("table") doesn't match anything.

Boy did the jQuery designers screw up when they named this. It seems to be the most common source of confusion among newbies.