简体   繁体   中英

Jquery add and remove child classes

I am trying to show an X next to a tab on my page when the tab is clicked and I am having problems showing and hiding the X. between the tabs. I am getting the parent tag from.

$('.tabs .tab-links a').on('click', function(e) {
    var currentValue = $(this).parent('li')
});

My problem is that I have a span within that LI and I cannot seem to access that span that has the X in it

<div class="tabs">
  <ul class="tab-links">
    <li>
      <a href="#tab1">Official Rules</a>
        <span class="close hidden">X</span>
    </li>
    <li>
      <a href="#tab2">Privacy Policy</a>
      <span class="close hidden">x</span>
    </li>
    <li>
      <a href="#tab3">Support</a>
      <span class="close hidden">X</span>
    </li>
  </ul>
</div>

Is there a way to add the X with like a removeClass('hidden') when the link is clicked with in that LI tag ?

You can try using .next("span") to target the next A 's element (the SPAN )
but the best way is first refer to a parent and than find the desired selector:

.closest("li").find("span")

in your example:

$('.tabs .tab-links a').on('click', function(e) {
    var $span = $(this).closest('li').find("span");
    $span.toggleClass("hidden"); // OR whatever you want to do with $span
});

So going first for .closest() allows you to (one nice day) change the inner HTML of the LI and still get that span even if it's not any more .next() to the clicked element.

You can use jQuery's siblings and remove the class of an element

$('.tabs .tab-links a').on('click', function(e) {
    $(this).parents("ul").find("span").addClass("hidden");
   $(this).siblings("span").toggleClass("hidden");

}); 

Check JS fiddle

Check updated JS fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM