skip to Main Content

I want to hide .tab when I click .btn in another div.
but this code doesn’t work.
I don’t want to use filter by index for some reasons

How Can I fix it?

$(".btn").click(function() {
  var tabname = $(this).parent().attr("id")

  $(".tab").filter(function() {
    return $(this).attr("value") === tabname
  }).hide()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="tab01">
  <button class="btn"> button</button>
</div>
<div id="tab02">
  <button class="btn"> button</button>
</div>
<div id="tab03">
  <button class="btn"> button</button>
</div>

<div class="tab-list">
  <button class="tab" value="#tab01">This is button 1</button>
  <button class="tab" value="#tab02">This is button 2</button>
  <button class="tab" value="#tab03">This is button 3</button>
</div>

2

Answers


  1. Basically I fixed the code, but instead of hiding do you not want to hide all then show the selected?

    $(".btn").click(function() {
      var tabname = $(this).parent().attr("id")
      console.log(tabname)
    
      $(".tab").filter(function(index, elem) {
        return $(elem).attr("value") === '#' + tabname
      }).hide()
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <div id="tab01">
      <button class="btn"> tab 1</button>
    </div>
    <div id="tab02">
      <button class="btn"> tab 2</button>
    </div>
    <div id="tab03">
      <button class="btn"> tab 3</button>
    </div>
    
    <div class="tab-list">
      <button class="tab" value="#tab01">This is tab content 1</button>
      <button class="tab" value="#tab02">This is tab content 2</button>
      <button class="tab" value="#tab03">This is tab content 3</button>
    </div>
    Login or Signup to reply.
  2. Here is a solution with a CSS-selector instead of a filter:

    $(".btn").click(function() {
     let sel='.tab[value="#'+this.closest("div").id+'"]';
     // console.log(sel)
     $(sel).hide()
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <div id="tab01">
      <button class="btn"> button</button>
    </div>
    <div id="tab02">
      <button class="btn"> button</button>
    </div>
    <div id="tab03">
      <button class="btn"> button</button>
    </div>
    
    <div class="tab-list">
      <button class="tab" value="#tab01">This is button 1</button>
      <button class="tab" value="#tab02">This is button 2</button>
      <button class="tab" value="#tab03">This is button 3</button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search