How to select the previous sibling of an element
- Published at
- Updated at
- Reading time
- 1min
Jim Nielsen blogged about a mind-boggling feature of the new :has()
pseudo-class. It's not well supported yet, but this CSS addition unlocks countless use cases that Frontend engineers have been dreaming of for years.
MDN Compat Data (source)
![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() | ![]() |
105 | 105 | 105 | 103* | 103 | 15.4 | 15.4 | 20.0 | 105 |
* Please check MDN for more details.
I always thought :has()
is only the long-awaited "parent selector", but Jim shared that it's the "previous sibling selector", too! 🤯
/*
Select every <a> element that's a child of
a <p> element that directly precedes an <hr> element.
*/
p:has(+ hr) a { /* ... */ }
If you want to learn more, head over to Jim's blog. It's a great one!
Was this snippet helpful?
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 4 days ago.
Yes? Cool! You might want to check out Web Weekly for more snippets. The last edition went out 4 days ago.