akonsu
akonsu

Reputation: 29538

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.

Upvotes: 24

Views: 21990

Answers (4)

Jorge Israel Pe&#241;a
Jorge Israel Pe&#241;a

Reputation: 38576

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.

Upvotes: 6

David Thomas
David Thomas

Reputation: 253308

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...).

Upvotes: 13

Jeff Rupert
Jeff Rupert

Reputation: 4840

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.

Upvotes: 2

MacMac
MacMac

Reputation: 35301

ul li {
    /* styles */
}

Is this what you're asking for?

Upvotes: -6

Related Questions