Reputation: 11
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
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
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
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
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