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

Time:01-06

I have next HTML:

<table>
    <tr>
        <td>
            <span >One</span>
            <span >Two</span>
            <span >Three</span>
        </td>
    </tr>
    <tr>
        <td>
            <span >One</span>
            <span >Two</span>
            <span >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?

CodePudding user response:

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");
    });
});

CodePudding user response:

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 >One</span>
      <span >Two</span>
      <span >Three</span>
    </td>
  </tr>
  <tr>
    <td>
      <span >One</span>
      <span >Two</span>
      <span >Three</span>
    </td>
  </tr>
</table>

CodePudding user response:

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 >One</span>
      <span >Two</span>
      <span >Three</span>
    </td>
  </tr>
  <tr>
    <td>
      <span >One</span>
      <span >Two</span>
      <span >Three</span>
    </td>
  </tr>
</table>

  •  Tags:  
  • Related