Bogdan
Bogdan

Reputation: 382

jQuery: how to remove class from nearest elements in parent div?

I have next HTML:

<table>
    <tr>
        <td>
            <span class="btn active">One</span>
            <span class="btn">Two</span>
            <span class="btn">Three</span>
        </td>
    </tr>
    <tr>
        <td>
            <span class="btn">One</span>
            <span class="btn active">Two</span>
            <span class="btn">Three</span>
        </td>
    </tr>
</table>

I try to add class active to the current clicked element:

$(document).ready(function() {
    $(".btn").click(function() {
        $(".btn").removeClass("active");
        $(this).addClass("active");
    });
});

it works, but removes active class from all other spans.

How to remove active class only from the nearest elements, for example only inside the parent td?

Upvotes: 0

Views: 1189

Answers (3)

Esszed
Esszed

Reputation: 607

You can make sure you are removing the class only from the children of the parent element of the clicked span.

$(document).ready(function() {
    $(".btn").click(function() {
        $(this.parentElement.childNodes).removeClass("active");
        $(this).addClass("active");
    });
});

Upvotes: 2

Bogdan
Bogdan

Reputation: 382

I find solution:

$(document).ready(function() {
  $(".btn").click(function() {
    $(this).parent().find('.btn').removeClass("active");
    $(this).addClass("active");
  });
});
.active {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <span class="btn active">One</span>
      <span class="btn">Two</span>
      <span class="btn">Three</span>
    </td>
  </tr>
  <tr>
    <td>
      <span class="btn">One</span>
      <span class="btn active">Two</span>
      <span class="btn">Three</span>
    </td>
  </tr>
</table>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337626

To do what you require you can use the this keyword in the event handler to reference the element which raised the event. From there you can use jQuery's DOM traversal methods, in this case siblings(), to find the related elements and change their classes.

jQuery($ => {
  $(".btn").click(function() {
    $(this).addClass('active').siblings('span').removeClass("active");
  });
});
.active { color: #C00; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <span class="btn active">One</span>
      <span class="btn">Two</span>
      <span class="btn">Three</span>
    </td>
  </tr>
  <tr>
    <td>
      <span class="btn">One</span>
      <span class="btn active">Two</span>
      <span class="btn">Three</span>
    </td>
  </tr>
</table>

Upvotes: 1

Related Questions