Selecting the last nested item
How do I select the last has-errors
div below?
<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>
I can select the first has-errors
one using:
.form-block .form-group.has-errors:first-child {
background-color: blue;
}
But last-child
doesn't work above. How to choose the latest copy .form-group.has-errors
?
source to share
With CSS this will be tough unless there are certain rules - as always, this is the second of the last. In short, you are asking how last-of-class
, which does not exist. There is last-of-type
, but this only applies to the element type ( div
, p
etc.), not to classes.
Next best option is some vanilla JS to grab the last element with a class .form-group.has-error
.
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 changed:
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>
source to share
Selecting the last sibling with a class is not possible using CSS alone. You only have:
-
:last-child
- the last child of the parent element -
:last-of-type
- the last element of this type in the parent - Not the first:
selector ~ selector
Since you have it .form-group
, I am assuming you are using Bootstrap, which is why you are using jQuery. This will do the trick:
$('section').each(function(){
$('.has-errors', $(this)).last().css({borderBottom: '1px solid red'})
})
source to share