Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Select a div that contains a div having specific attribute value or class

I want to select a div that contains another div with specific class or specific attribute value. I have tried these: (but it selects the child not the parent/container)

div div[data-value="hi"]
div>div[data-value="hi"]
div div.any
div>div.any

(example) the one with attribute value:

<div>
<div data-value="hi">example</div>
</div>

(example) or the one below with class:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div>
<div class="any">example</div>
</div>

Please do not suggest nth-child as their will be couple of div and div position is random as the below example:

<div>
<div class="other">example</div>
</div>
<div>
<div class="any">example</div>
</div>
<div>
<div class="other">example</div>
</div>
<div>
<div class="other">example</div>
</div>

Please let me know if it even possible with only CSS, Thank you for your help.

>Solution :

If I’ve understood correctly and you want to target the PARENT should it contain a child with a given class or attribute, then you want the :has pseudo-selector. Note, that it isn’t available in all browsers/versions yet but has good availability see: Can I Use :has selector

div {
  height: 50px;
  width: 100%;
   
}

div:has(div.other) {
  background: red;
}

div:has(div[data-value="hi"]) {
  background: orange;
}
<div>
<div class="other">example</div>
</div>
<div>
<div class="any">example</div>
</div>
<div>
<div class="other">example</div>
</div>
<div>
<div data-value="hi">example</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading