Search code examples
htmlcssattributes

CSS to target div that contains specific attributre or tag?


I'm working with a POS system that generates a website. Large parts of the code are proprietary and thus I can't edit a lot of things.

I have an outputted category listing that floats some images as categories. I want to hide the first 3 listed on the main page. I tried targeting the containing div with div:nth-child(1), which worked, but each sub-page it also hides them as well.

Unfortunately ALL non-main pages have only ONE class added to the body and main divs so I can't do a per-category ID or style, or per-page.

What I do have is an image tag that will be the same on each page. So I have tried the following:

img[src="theimage.png"] {
display: none; 
}

This also works great, BUT it only hides the image. Is there any way I can target the surrounding divs using that code or a variation of that code? For reference here is a basic structure:

<div class="cCategoryDivContainer col-xs-12 col-sm-6 col-md-6 col-lg-4">
     <div class="cCategoryDiv">
         <div class="cItemTitleDiv">
             <p class="cCategoryTitle">Category Title</p>
         </div>
         <div class="cItemImageDiv">
             <span class="cItemImageHelper"></span>
             <a href="#"><img class="cItemImage" src="theimage.png"></a>
         </div>
     </div>
 </div>

Essentially I want to target the div with class cCategoryDivContainer IF the src of the inside image is set to theimage.png.

Is this possible?


Solution

  • Actually you can in modern browsers. See support: https://caniuse.com/?search=has

    .cCategoryDiv:has(img[src="theimage.png"]) {
      display: none;
    }
    <div class="cCategoryDivContainer col-xs-12 col-sm-6 col-md-6 col-lg-4">
         <div class="cCategoryDiv">
             <div class="cItemTitleDiv">
                 <p class="cCategoryTitle">Category Title</p>
             </div>
             <div class="cItemImageDiv">
                 <span class="cItemImageHelper"></span>
                 <a href="#"><img class="cItemImage" src="theimage.png"></a>
             </div>
         </div>
         <div class="cCategoryDiv">
             <div class="cItemTitleDiv">
                 <p class="cCategoryTitle">Category Title</p>
             </div>
             <div class="cItemImageDiv">
                 <span class="cItemImageHelper"></span>
                 <a href="#"><img class="cItemImage" src="anotherimage.png"></a>
             </div>
         </div>
     </div>