Select element based on child class

后端 未结 4 2051
北恋
北恋 2021-01-07 19:26

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

    list that has
4条回答
  •  Happy的楠姐
    2021-01-07 19:43

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

提交回复
热议问题