I can use the adjacent selector like this:
/* When c and c are adjacent, color the second c red */
.c + .c {
background-color: red;
}
But how to do the same thing when the “.c” is nested?
<div class="a">
<div class="b">
<div class="c"></div>
</div>
</div>
<div class="a">
<div class="b">
<div class="c"></div>
</div>
</div>
/* Does not work */
.a .b .c + .a .b .c {
background-color: red;
}
For adjacent selector +
, the two selectors must be on the same level.
So it must be .a + .a
, since they are the only adjacent elements in your snippet. Then you can select the second .a
‘s desendent: .a + .a .b .c
. After that you could restrict the first .a
to make sure it also has desendent .b .c
using :has()
pseudo class:
'.a:has(.b .c) + .a .b .c'
const target = document.querySelector('.a:has(.b .c) + .a .b .c');
console.log(target);
<div class="a">
<div class="b">
<div class="c">1</div>
</div>
</div>
<div class="a">
<div class="b">
<div class="c">2</div>
</div>
</div>