Complex CSS selector for parent of active child
Unfortunately, there's no way to do that with CSS.
It's not very difficult with JavaScript though:
// JavaScript code:
document.getElementsByClassName("active")[0].parentNode;
// jQuery code:
$('.active').parent().get(0); // This would be the <a>'s parent <li>.
According to Wikipedia:
Selectors are unable to ascend
CSS offers no way to select a parent or ancestor of element that satisfies certain criteria. A more advanced selector scheme (such as XPath) would enable more sophisticated stylesheets. However, the major reasons for the CSS Working Group rejecting proposals for parent selectors are related to browser performance and incremental rendering issues.
And for anyone searching SO in future, this might also be referred to as an ancestor selector.
Update:
The Selectors Level 4 Spec allows you to select which part of the select is the subject:
The subject of the selector can be explicitly identified by prepending a dollar sign ($) to one of the compound selectors in a selector. Although the element structure that the selector represents is the same with or without the dollar sign, indicating the subject in this way can change which compound selector represents the subject in that structure.
Example 1:
For example, the following selector represents a list item LI unique child of an ordered list OL:
OL > LI:only-child
However the following one represents an ordered list OL having a unique child, that child being a LI:
$OL > LI:only-child
The structures represented by these two selectors are the same, but the subjects of the selectors are not.
Although this isn't available (currently, November 2011) in any browser or as a selector in jQuery.
Late to the party again but for what it's worth it is possible using jQuery to be a little more succinct. In my case I needed to find the <ul>
parent tag for a <span>
tag contained in the child <li>
. jQuery has the :has
selector so it's possible to identify a parent by the children it contains (updated per @Afrowave's comment ref: https://api.jquery.com/has-selector/):
$("ul").has("#someId")
will select the ul
element that has a child element with id someId. Or to answer the original question, something like the following should do the trick (untested):
$("li").has(".active")