views:

32

answers:

4

hello,

is there a way in css to select an element which has a subelement with given class?

i want to apply a style to a <ul> list that has <li> with a particular class.

thanks konstantin

A: 
ul li {
    /* styles */
}

Is this what you're asking for?

YouBook
no. i need to set style for ul
akonsu
+2  A: 

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.

Jeff Rupert
+5  A: 

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

David Thomas
@David Thomas: +1, and you have an unclosed quote in your code example.
Jeff Rupert
@Jeff Rupert, thanks for the +1 and correction (edited to correct) =)
David Thomas
Haha, I'm on the same boat as you regarding Javascript and jQuery. Been reading some books to get up to speed though. Javascript: The Good Parts and jQuery in Action, Second Edition
Jorge Israel Peña
*jQuery: Novice to Ninja* (from O'Reilly) is pretty good. Though I've yet to come across the `.shuriken(200)` method... =)
David Thomas
My previous comment is wrong, the book's by Sitepoint (not O'Reilly).
David Thomas
+2  A: 

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.

Jorge Israel Peña
+1 for a more versatile (than mine) jQuery approach.
David Thomas