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 >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 >example</div>
</div>
<div>
<div >example</div>
</div>
<div>
<div >example</div>
</div>
<div>
<div >example</div>
</div>
Please let me know if it even possible with only CSS, Thank you for your help.
CodePudding user response:
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 >example</div>
</div>
<div>
<div >example</div>
</div>
<div>
<div >example</div>
</div>
<div>
<div data-value="hi">example</div>
</div>
CodePudding user response:
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 >example</div>
</div>
<div>
<div >example</div>
</div>
<div>
<div >example</div>
</div>