0

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:

<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.

Rains
  • 29
  • 4

2 Answers2

0

just directly select its class or data-value

div > .any {
  background: red;
}

div > [data-value="other"] {
  background: blue;
}
<div>
<div data-value="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>
Matias Bertoni
  • 500
  • 2
  • 7
  • Guess the parent div has its own background color and some padding, so directly selecting the child, and changing the background color of it will not help. – Rains Dec 15 '22 at 18:45
0

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>
Jordan
  • 1,390
  • 2
  • 9
  • 24
  • Hey thank you so much, I also have found that myself. Yes, doesn't have support everywhere, but the majority supports it. – Rains Dec 15 '22 at 18:55