As great as CSS is, there is one thing that it lacks and that is a parent selector. The supposed reason for its nonexistence is performance concerns.
People forget that the CSS specification as it currently stands offers many selector features which when used incorrectly could be considered bad for performance.
I think justifying the lack of
forEach method because it is less performant than a native
while and can introduced performance issues.
Like everything else in CSS, if you’re in the camp that opposes a
:parent selector, don’t ruin it for everyone else. You decide what you want to use when you’re writing CSS, not the specification.
A little use-case I encountered recently was custom styled radio elements. I have a radio input inside of a label which resembled something like this:
<label><input type="radio" name="myRadio" value="1"> My Radio</label>
In my CSS I then hid the input element and styled the label so I could have a custom styled input. However, I couldn’t use CSS and the
:checked attribute because you can’t reference the parent element.
In the end I had to resort to use a DIV which contained the label and input to do the job. The point is, while I found another solution, my original solution would have been the most ideal.
Even if a parent selector were to be introduced, it isn’t like I would use it for anything other than targeting the direct parent of an element.
I would only ever need the direct parent of an element, surely that wouldn’t cause much of a performance hit? It’s the inverse of
:first-child or the direct descendant selector
Selectors Level 4
There is a little known W3C specification called Selectors Level 4 and a parent selector might exist in the spec. Another stumbling block being it will take a long time for it to be supported well enough to use any new feature.
Someone has actually created a jQuery plugin/polyfill based on ideas from the Selectors Level 4 specification which you can checkout here.
It looks like a well-designed plugin, but honestly it might be overkill if you can just work around the lack of
:parent selector instead.
Will there be a CSS parent selector in the future, what will it look like and do we really need one? I guess time will tell.