How to get a specific upper class of $(this) in jquery

Viewed 483

I have the following html.

<div class="new-row>
   <img class="trash" src = "trash.png">
   <img class="trash" src = "trash.png">
</div>
<div class="new-row>
    <img class="trash" src = "trash.png">
    <img class="trash" src = "trash.png">
</div>

Also I have the following jquery code

$(".trash").on("click",trashClicked);

How can I get the number of (".trash") in each new-row class. I don't want to get the total number of img tags with class trash. I want to get the specific number of img tags with class trash when a trash image is clicked in specific new -row

1 Answers

Inside trashClicked, this will refer to the specific img that was clicked. You can then work from there to figure out how many .trash imgs there are in that row:

  1. Your img elements are siblings of one another, so you could use siblings:

    var count = $(this).siblings().length + 1; // + 1 for the one we're calling it on
    
  2. A more general solution would use closest to find the enclosing .new-row, and then find to find all of the .trash elements, even if they're at different levels.

    var count = $(this).closest(".new-row").find(".trash).length;
    

It's well worth your time to read through the jQuery API, beginning to end. It doesn't take long, and it repays the time you spend doing it almost immediately.

Related