Search code examples
htmlcsscss-selectors

Check if element exists, then apply css


My HTML code is basically

<div class="a">
  <div class="b">
    ...
  </div>
</div>
<div class="c">
  ...
</div>

I now want to apply display: none; to c, but only if b exists. a and c always exist.

My approach was

.a .b ~ .c {
  display: none;
}

Solution

  • Edit: This can now be achieved purely in CSS (with the exception that Firefox still needs to integrate the :has selector in April 2023):

     .a:has(.b) ~ .c {
         display: none;
     }
    

    Old Answer

    This should work for you:

    var b = document.querySelector('.b');
    
    if (b) {
      document.querySelector('.c').style.display = 'none';
    }
    <div class="a">a
      <div class="b">b</div>
    </div>
    
    <div class="c">c</div>

    Obviously, JavaScript is required but just a touch. You could add the document.querySelector('.b) to the if statement instead of saving it to a variable as well.

    Edit: Just a bit of clarity on what's wrong with your code - you're first selecting .a .b which will select the b class if it's a descendant of the a class, then you're using the general sibling combinator (subsequent-sibling combinator), but it won't select the c class. This is because the c class is outside of the a element and is therefore not a descendant of your a class. A pure CSS solution would be having your c class inside of your a element, which would make your current CSS work and the JavaScript wouldn't be needed. For example, your HTML would look like this:

    .a .b ~ .c {
       display: none;
    }
    <div class="a">a
        <div class="b">b</div>
        <div class="c">c</div>
    </div>

    On a sidenote, the general sibling combinator ~ operator will look for any subsequent element that comes after b with a class of c. If you only wanted to apply it to the first element with a class of c that comes after b, consider using the adjacent sibling selector +, otherwise known as the 'next-sibling combinator' instead.