How to select the last element that has a specific class?

Viewed 262

I wanted to select the last element that has a class of .completed. How do I do that?

Here's my HTML:

<div class="steps">
    <div class="progress completed"></div>
    <div class="progress completed"></div>
    <div class="progress"></div>
    <div class="progress"></div>
</div>

I've tried using this:

.progress.completed:last-of-type {
    background-color: #ccc;
}

But it doesn't work.

2 Answers

This should ideally be done by assigning a class to the last occurring item.

To do it programmatically, we can use querySelectorAll to get a list of all items, from which we can get the last element and add a class to it.

[...document.querySelectorAll('.progress.completed')].slice(-1)[0].classList.add('last-item');
.last-item{
  background-color:#ccc;
}
<div class="steps">
  <div class="progress completed">a</div>
  <div class="progress completed">a</div>
  <div class="progress">a</div>
  <div class="progress">a</div>
</div>

There is no (good) way to solve this problem in its current state with CSS. The best solution is to add an extra class to the last completed div with the help of javaScript or jQuery.

JavaScript or jQuery will find the last child of the parent and give you ability to change it by adding classes and styles.

.last{
    background-color: #ccc;
}

with jQuery

$(".progress.completed").last().addClass("last");
Related