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
Without using
:has()
this is not possible. So in this case you rely on usingJavaScript
or alter theHTML
.But since editing the HTML structure is not possible in your case lets use
JavaScript
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.