'CSS Select a child with parents that meet multiple conditions

I'm trying to select the element <div name="inner">a-inner</div> which is the child of the first div node.

To do so, I'm trying to create a selector which is a logical AND that the element has SOME parent with the defined property.

I don't know what the parent hierarchy looks like beforehand, so I can't simply do: [role="foo"] > [letter=A] > [name=inner], because the hierarchy may not turn out that way.

<div role="foo">
 <div letter="A">
   <div name="inner">a-inner</div>
 </div>
 <div letter="B">
   <div name="inner">b-inner</div>
 </div>
</div>

In the Chrome console (using $$ as shorthand for document.querySelectorAll, I first tried: $$('[role=foo]>[name=inner],[letter=A]>[name=inner]') which returned the element

But then when I changed foo tobar as in $$('[role=bar]>[name=inner],[letter=A]>[name=inner]'), it still returned that same element.

I want the selector to select elements which have a parent with a list of properties.

How do I format this?

The order of which property comes first in the hierarchy is irrelevant, I just want to make sure that each selected element has some parent with the required property.



Solution 1:[1]

You can make use of the pseudo-selector first-of-type:

div[role="foo"] > div:first-of-type > div[name="inner"] {
  color: red;
}
<div role="foo">
 <div letter="A">
   <div name="inner">a-inner</div>
 </div>
 <div letter="B">
   <div name="inner">b-inner</div>
 </div>
</div>

Or select based on the letter attribute:

div[role="foo"] > div[letter="A"] > div[name="inner"] {
  color: red;
}
<div role="foo">
 <div letter="A">
   <div name="inner">a-inner</div>
 </div>
 <div letter="B">
   <div name="inner">b-inner</div>
 </div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Obsidian Age