With CSS it will be tough unless there are some specific rules - like it's always the 2nd from last. In short what you're asking for is like last-of-class
, which doesn't exist. There is last-of-type
but that only applies to element type (div
, p
, etc), not to classes.
The next best option is some vanilla JS to grab the last element with the .form-group.has-error
class.
const hasErrors = document.querySelectorAll('.form-group.has-errors');
hasErrors[hasErrors.length -1].style.color = 'red';
<section class="form-block">
<div class="form-group has-errors">
ERROR!
</div>
<div class="form-group has-errors">
ERROR!
</div>
<div class="form-group">
stuff
</div>
</section>
To make this useful for multiple form blocks on a page it could be modified to:
const formGroups = Array.from(document.querySelectorAll('.form-block'));
formGroups.forEach(function(block) {
const hasErrors = block.querySelectorAll('.form-group.has-errors');
hasErrors[hasErrors.length -1].style.color = 'red';
});
Form Block 1
<section class="form-block">
<div class="form-group has-errors">
ERROR!
</div>
<div class="form-group has-errors">
ERROR!
</div>
<div class="form-group">
stuff
</div>
</section>
Form Block 2
<section class="form-block">
<div class="form-group has-errors">
ERROR!
</div>
<div class="form-group has-errors">
ERROR!
</div>
<div class="form-group">
stuff
</div>
</section>