Dhoni
Dhoni

Reputation: 1234

siblings() in jQuery is not working

I tried to achieve tabs using jQuery. Making the current tab class active is working, but to make its sibling's class null is not working.

jQuery(document).ready(function() {
  jQuery('.container .tab-links a').on('click', function(e) {

    var currentAttrValue = jQuery(this).attr('href');
    console.log(currentAttrValue);
    // jQuery(this).addClass('active').siblings.removeClass('active');
    // Show/Hide Tabs
    //jQuery(currentAttrValue).show().siblings().hide();

    // Change/remove current tab to active
    jQuery(this).addClass('active');
    jQuery(this).siblings().find('a').removeClass('active');
    jQuery('each_tab').not(currentAttrValue).css("display", "none");
    jQuery(currentAttrValue).css("display", "block");

    e.preventDefault();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section id="features">
  <header>
    <div class="features-switcher">
      <div class="container">
        <ul class="tab-links">
          <li>
            <a class="active" href="#tab1">
              <span>tab one</span>
            </a>
          </li>
          <li>
            <a class="" href="#tab2">
              <span>tab two</span>
            </a>
          </li>
          <li>
            <a class="" href="#tab3">
              <span>tab three</span>
            </a>
          </li>
        </ul>
      </div>
    </div>
    <hr>
  </header>
  <div class="tab-content">
    <div id="tab1" class="tab--active">
      <section class="container">
        <h2> content of tab 1</h2>
        <hr>
      </section>
    </div>
    <div id="tab2" class="tab--inactive">
      <section class="container">
        <h2> content of tab 2</h2>
      </section>
    </div>
    <div id="tab3" class="tab--inactive">
      <section class="container">
        <h2> content of tab 3</h2>
      </section>
    </div>
  </div>
</section>

Upvotes: 0

Views: 1704

Answers (2)

Paul Roub
Paul Roub

Reputation: 36438

The <a> elements in questions have no siblings. The containing <li> elements do.

Target those — and their descendant <a> tags — instead, with:

jQuery(this).parent().siblings('li').find('a').removeClass('active');

Your each_tab query can be replaced with:

jQuery('.tab-content > div').not(currentAttrValue).
   hide().  
   addClass('tab--inactive').
   removeClass('tab--active');
jQuery(currentAttrValue).
   show().
   addClass('tab--active').
   removeClass('tab--inactive');

Upvotes: 3

elixenide
elixenide

Reputation: 44831

You're selecting the <a> tags, then calling jQuery(this).siblings(). But the <a> tags don't have any siblings; it's their parents (the <li> tags) that have siblings. You should be calling jQuery(this).parent().siblings(), instead.

Upvotes: 1

Related Questions