Todd Jemar Alexander
Todd Jemar Alexander

Reputation: 25

How to toggleClass only the clicked node

I have a table that has toggled rows of the .parent after a while loop. My JS is below and as you can see I also want to toggleClass of the .parentelement so the header row can be highlighted when I click it. But with the current code all .parent nodes are toggling the class when one is clicked. How can I change this so only the .parent that I click on toggles?

<script type="text/javascript">  
$(document).ready(function () {

   $(".child").hide();

   function getChildren($row) {
      var children = [];
      while ($row.next().hasClass('child')) {
         children.push($row.next());
         $row = $row.next();
      }
      return children;
   }

   $('.parent').on('click', function () {

      $('.parent').toggleClass('td-active');

      var children = getChildren($(this));
      $.each(children, function () {
         $(this).toggle(1000);

      })
   });

})
</script>

Upvotes: 1

Views: 1588

Answers (2)

fanfavorite
fanfavorite

Reputation: 5199

$('.parent').toggleClass('td-active');

TO:

$(this).toggleClass('td-active');

Upvotes: 1

Pitsanu Swangpheaw
Pitsanu Swangpheaw

Reputation: 672

$('.parent').on('click', function() {

    $(this).toggleClass('td-active');

    var children = getChildren($(this));
    $.each(children, function() {
        $(this).toggle(1000);

    })
});

Upvotes: 0

Related Questions