javascriptcsscss-selectors

How to target from one parent's child to another parent element?


Suppose I have four div classes as follow:

dFir
dSec
dSec
dThi

In this div, I have one li and have the following classes:

first
sec
sec
thi

I have to target from the first class to all dSec classes and change the background-color to #000.

The HTML I have written as follows"

<div class="dFir">
  <li class="first">fir</li>
</div>

<div class="dSec">
  <li class="sec">sec</li>
</div>

<div class="dSec">
  <li class="sec">thi</li>
</div>

<div class="dThi">
  <li class="thi">fou</li>
</div>

The css I have written as follows:

.first.active ~ .dSec{
   background-color: #000;
}

The js I have written as follow:

const free = document.querySelectorAll(".first");

    free.forEach(uff => {
        uff.addEventListener("click", () => {
            uff.classList.toggle("active");
        });
    });

I have to target from the first class to all dSec classes and change the background-color to #000.

const free = document.querySelectorAll(".first");

free.forEach(uff => {
  uff.addEventListener("click", () => {
    uff.classList.toggle("active");
  });
});
.first.active~.dSec {
  background-color: #000;
}
<div class="dFir">
  <li class="first">fir</li>
</div>

<div class="dSec">
  <li class="sec">sec</li>
</div>

<div class="dSec">
  <li class="sec">thi</li>
</div>

<div class="dThi">
  <li class="thi">fou</li>
</div>


Solution

  • I guess you can do it by CSS by using:

    const free = document.querySelectorAll(".first");
    
    free.forEach(uff => {
      uff.addEventListener("click", () => {
        uff.classList.toggle("active");
      });
    });
    .dFir:has(> .first.active) ~ .dSec {
      background-color: #000;
    }
    <div class="dFir">
      <li class="first">fir</li>
    </div>
    
    <div class="dSec">
      <li class="sec">sec</li>
    </div>
    
    <div class="dSec">
      <li class="sec">thi</li>
    </div>
    
    <div class="dThi">
      <li class="thi">fou</li>
    </div>

    The W3C's Selectors Level 4 Working Draft includes a :has() pseudo-class that provides this capability, among others, then, you can target the siblings.