Use CSS to hide the parent of a selected element

css
11,708

Solution 1

Well you code was wrong <p class="badChild"/> is wrong because <p> is a block element and ends like this <p class="badChild"></p> i have updated the question and coming to your problem there is no method to do this with css only because css allows you to select child, first child, sibling but not the parent element so javascript or jquery is the only option.

If there was a way to do it, it would be in either of the current CSS selectors specs:


The Selectors Level 4 Working Draft includes a :has() pseudo-class that works the same as the jQuery implementation. As of 2015, this is not available in any browser.

Using :has() the original question could be solved with this:

li:has(> a.active) { /* styles to apply to the li tag */ }

In the meantime, you'll have to resort to JavaScript if you need to select a parent element.

$(document).ready(function(){
    $('.badChild').parent('.parent').hide();
});

Solution 2

No, it is impossible to address parent from children with CSS. You should use JavaScript to do so, for example with jQuery .parent() method.

Share:
11,708
Don P
Author by

Don P

@ Facebook currently

Updated on June 09, 2022

Comments

  • Don P
    Don P almost 2 years

    Using only CSS, is it possible to hide a parent element if a child element does not have a class?

    <!-- hide this -->
    <div class="parent">
      <p class="badChild" />
    </div>
    
    <!-- do not hide this -->
    <div class="parent">
      <p class="goodChild" />
    </div>
    

    Unfortunately, I cannot change the markup of the page. I can only add CSS rules.

  • Zach Saucier
    Zach Saucier about 8 years
    Suggesting something as large as jQuery for the equivalent elem.parentNode in vanilla JS is bad practice.
  • Andy  Gee
    Andy Gee over 3 years
    @ZachSaucier I agree with the sentiment but when 79% of websites run jQuery and there's no widely available CSS solution, it provides the simplest to implement solution for the majority of SO's copy/paste web devs. Any user capable of implementing a vanilla JS solution would also know this. Perhaps a vanilla JS implementation would be preferable to criticism of an ultimately accepted answer.