r/css • u/KeinZantezuken • 9d ago
Question Last of specific selector
I have a dynamic DOM tree with various element count:
[parent]:
.child_class_special
.child_class_entry
.child_class_entry
.child_class_entry
.child_class_pre_special
.child_class_special
.child_class_entry
.child_class_entry
What I want is to target last possible " .child_class_special", however, as I said, the number of child elements in parent is varying, there could be 3 " .child_class_special", or could be 7.
This:
.parent .child_class_special:not(:has(~ .child_class_special))
works but it is uggo. Any ideas for more concise selector?
5
Upvotes
2
u/sk_sushellx 9d ago
no cleaner native CSS selector exists for this unfortunately 💀 the
:not(:has(~ .child_class_special))pattern is genuinely the correct modern approach even if it looks ugly. you could alias it with a custom property or handle it in JS withquerySelectorAll('.child_class_special')and grab the last index, which is more readable even if it's more code. the CSS solution you have is actually the most concise pure-CSS answer available right now lol