Home > Blockchain >  Hide first closest parent element using javascript (or jquery)
Hide first closest parent element using javascript (or jquery)

Time:05-24

I want to hide a html class when button clicked.

The html structure is like this:

<thead>
  <tr >
     <th>
         <button >Show Employee</button>
     </th>
  </tr>
</thead>
<tbody >
   <tr >
      <td style="width: 300px" >Employee 1</td>
   </tr>
   <tr >
      <td style="width: 300px" >Employee 2</td>
   </tr>
</tbody>
<tbody >
   <tr >
      <td style="width: 300px" >Employee 1</td>
   </tr>
   <tr >
      <td style="width: 300px" >Employee 2</td>
   </tr>
</tbody>

Also I can have more than one .emp class.

I've tried something like code bellow, but still not working (it hide all element with .emp class)

$('.show-emp').click(function() {
   $(this).closest(".emp").hide();
});

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.

CodePudding user response:

.closest() finds the closest parent element that matches the selector, but .emp isn't a parent of .show-emp.

You want to go up to the thead, then find the first sibling after it that matches the selector.

.nextAll() will find all the following siblings that match. Use .first() to get the first one.

$('.show-emp').click(function() {
  $(this).closest("thead").nextAll(".emp").first().toggle();
  $(this).text(function(i, text) {
    return text == 'Show Employee' ? 'Hide Employee' : 'Show Employee';
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <thead>
    <tr >
      <th>
        <button >Hide Employee</button>
      </th>
    </tr>
  </thead>
  <tbody >
    <tr >
      <td style="width: 300px" >Employee 1</td>
    </tr>
    <tr >
      <td style="width: 300px" >Employee 2</td>
    </tr>
  </tbody>
  <tbody >
    <tr >
      <td style="width: 300px" >Employee 3</td>
    </tr>
    <tr >
      <td style="width: 300px" >Employee 4</td>
    </tr>
  </tbody>
</table>

CodePudding user response:

First of all correct your markup and jquery properly.

  1. check your <button tag
  2. Jquery code here ('.show-emp')

You can achieve it many way. one of the below way.

$('.show-emp').click(function() {
   $(this).parents().siblings('.emp').first().hide();
   
   // to hide only first sibling then use //first()
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
  <tr >
     <th>
         <button > Btn </button>
     </th>
  </tr>
</thead>
<tbody >
   <tr >
      <th style="width: 300px" >Employee 1</th>
   </tr>
   <tr >
      <th style="width: 300px" >Employee 2</th>
   </tr>
</tbody>
</table>

  • Related