Select element based on child class
Is开发者_开发问答 there a way in CSS to select an element which has a sub-element with given class?
I want to apply a style to a <ul>
list that has <li>
with a particular class.
This isn't possible with css, since you're working against the cascade by selecting an ancestor based on a descendant.
The best I can offer and suggest is a jQuery approach:
$(document).ready(
function() {
$('.givenClassName').parent().addClass('something');
}
);
This finds the element with the givenClassName
and then selects its parent element and adds the class something
to that element.
@Blaenk suggests an alternate approach, which is more versatile (his approach doesn't require the ancestor element to be the parent of the element you're selecting by).
Obviously other JS libraries, and JS all by itself, can achieve the same effect, though I can't offer particular advice, since I'm still only just familiarising myself with JS and mostly with jQuery (why yes, I am ashamed of myself...).
As far as I know, this is unfortunately not possible with CSS.
If you can use Javascript though, jQuery has a nice way of doing this using the closest()
method. The documentation for it even lists an example very similar to yours: selecting a ul that has an li of a particular class.
$("li.some-class").closest("ul");
Forgive me if this is not the best way to do it in jQuery. I'm actually new to jQuery and this is one of the methods I've learned so far, and it seemed fitting.
No. The CSS Cascade does not allow for this kind of selector.
The best solution in this case would be either to modify the DOM with JavaScript or to change up the resultant HTML to add classes to the ul
tags.
ul li {
/* styles */
}
Is this what you're asking for?
精彩评论