Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

catto's avatar
Level 1

Hide/show first closest parent element using javascript (or jquery)

I want to hide a html class when button clicked.

The html structure is like this:

<thead>
  <tr class="employee-list">
     <th>
         <button class="show-emp">Show Employee</button>
     </th>
  </tr>
</thead>
<tbody class="emp">
   <tr class="employee-list">
      <td style="width: 300px" class="text-center">Employee 1</td>
   </tr>
   <tr class="employee-list-last">
      <td style="width: 300px" class="text-center">Employee 2</td>
   </tr>
</tbody>
<tbody class="emp">
   <tr class="employee-list">
      <td style="width: 300px" class="text-center">Employee 1</td>
   </tr>
   <tr class="employee-list-last">
      <td style="width: 300px" class="text-center">Employee 2</td>
   </tr>
</tbody>

Also I can have more than one show-emp and .emp class (the markup is inside foreach loop).

I've tried something like code bellow, but still not working (it hide the first .emp in the table, not the closest one to the show-emp button)

$('.show-emp').click(function() {
   $(this).closest("table").find(".emp").first().toggle();
});

The ilustration how it works is like this: enter image description here

When show button clicked, it will only hide/show the employee list bellow it.

0 likes
1 reply
saifqureshi341's avatar

Try this.

$(document).on('click','.show-emp',function() {
   $(this).parents().eq(3).next().toggle();
});

Please or to participate in this conversation.