Evgeniy  Volkov
Evgeniy Volkov

Reputation: 11

How to select in each row the last element with certain class?

In each row there are some cells containing class .meow.
How do I select the last .meow element in each row?
The code below just selects all .meows...

$("tr").each(function(){
  $(".meow").css("border", "3px solid red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr> <td><div class="meow">Meow</div><td>
       <td>Woof</td>
       <td><div class="meow">Meow</div><td>
  </tr>
  <tr> <td> <div class="meow">Meow</div><td>
       <td><div class="meow">Meow</div></td>
       <td>Woof<td>
   </tr>
  </table>

Upvotes: 0

Views: 59

Answers (4)

Jackthomson
Jackthomson

Reputation: 644

Change

$("tr").each(function(){ $(".meow").css("border", "3px solid red"); });

to

$("tr").each(function(){ $(this).find(".meow:last").css("border", "3px solid red"); });

https://api.jquery.com/last-selector/

Upvotes: 1

Theo
Theo

Reputation: 885

Try it like this

$("tr").each(function(){
  $(this).find(".meow:last").css("border", "3px solid red");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr> <td><div class="meow">Meow</div><td>
       <td>Woof</td>
       <td><div class="meow">Meow</div><td>
  </tr>
  <tr> <td> <div class="meow">Meow</div><td>
       <td><div class="meow">Meow</div></td>
       <td>Woof<td>
   </tr>
  </table>

Upvotes: 3

George Kagan
George Kagan

Reputation: 6124

Use jQuery's last() function.
Also, you need to base your search off of the current tr, so use $(this).find().

$(this).find(".meow").last().css("border", "3px solid red");

Upvotes: 1

Don Rhummy
Don Rhummy

Reputation: 25830

You should just use querySelector:

document.querySelector( ".child:last-of-type" );

And you can use querySelector on elements too, so use it on each row.

https://jsfiddle.net/L5fdhs7d/

Upvotes: 2

Related Questions