skip to Main Content

Is it possible to apply CSS to an element that doesn’t have a specific element as a child?

I can’t use :has() because I need to support older browsers. A JavaScript solution is allowed.

See code example.

<!-- Element I want to hide -->
<div>
  <a class="link"> click me </a>
</div>

<!-- Element with <p> inside. I don't want to hide it. -->
<div>
  <a class="link">
    <p class="p-Inside-Link">click me</p>
  </a>
</div>

My attempt that did not work:

div a:not( > .p-Inside-Link){
    display: none;
}

2

Answers


  1. Without using :has() this is not possible. So in this case you rely on using JavaScript or alter the HTML.

    But since editing the HTML structure is not possible in your case lets use JavaScript

    // Select all divs that contain an element with class .link
    const links = document.querySelectorAll('div .link');
    
    // Filter the links to only divs that don't contain 
    // an class with .p-Inside-Link 
    const linksToHide = [...links].filter(link => !link.querySelector('.p-Inside-Link'));
    
    [...linksToHide].forEach(link => {
      // Use parentNode on the link element to hide the surounding div element
      link.parentNode.style.display = 'none';
    });
    <!-- Element I want to hide -->
    <div>
      <a class="link"> HIDE ME </a>
    </div>
    
    <!-- Element with <p> inside. I don't want to hide it. -->
    <div>
      <a class="link">
        <p class="p-Inside-Link">SHOW ME</p>
      </a>
    </div>
    Login or Signup to reply.
  2. Here is a simple solution. Loop through the .link anchors inside of a div. Then for each link check to see if p-inside-link doesn’t exist. If it doesn’t exist add a CSS class called hide. Then in CSS add a class for hide that has a display of none.

    Adding classes instead of modifying the style via javascript will give you more future capabilities.

    const links = document.querySelectorAll("div .link");
    
    links.forEach((link) => {
      if(!link.querySelector(".p-Inside-Link")){
        link.parentNode.classList.add("hide");
      }
    });
      
      .hide{display:none;}
    <!-- Element I want to hide -->
    <div>
      <a class="link"> click me </a>
    </div>
    
    <!-- Element with <p> inside. I don't want to hide it. -->
    <div>
      <a class="link">
        <p class="p-Inside-Link">click me (keep)</p>
      </a>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search