Snorlax Snorlax - 1 month ago 7
Sass (Sass) Question

Select absolute last element

I'm trying to select the absolute last element with a class. This can be nested inside a lot of elements, it can be its own element somewhere on the page, it can literally be anywhere. Here's what I've tried:

https://jsfiddle.net/cztpog87/

HTML:

<div>
<div class="total">
Money!
</div>
<div>
<div class="total">
Money!
</div>
</div>
<div class="total">
Money!
</div>
</div>
<div>
<div class="total">
Money!
</div>
<div>
<div class="total">
Money!
</div>
</div>
<div class="total">
Money!
</div>
<div class="total">
Money!
</div>
</div>


CSS:

.total:not(:last-of-type) {
display: none;
}

.total:not(:last-child) {
display: none;
}


As you can see, it doesn't remove ALL the elements. It removes some but definitely not all. What is the absolute best way to remove ALL but the last? SASS is also welcome.

Answer

Quite simply this is not possible with CSS as there is no nth-of-class selector

With Jquery it's simplicity itself with the .last function.

$(".total").last().addClass("highlight");
.total.highlight {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class="total">
    Money!
  </div>
  <div>
    <div class="total">
      Money!
    </div>
  </div>
  <div class="total">
    Money!
  </div>
</div>
<div>
  <div class="total">
    Money!
  </div>
  <div>
    <div class="total">
      Money!
    </div>
  </div>
  <div class="total">
    Money!
  </div>
  <div class="total">
    Money!
  </div>
</div>