2

In my app, I'm trying to add an active class to the proper section, and the logic is based on the .closest() method.

When I click on Span 2 I need to get the section with .--level-2, I can get the correct container--expanded, but when it goes to the section I get the upper one with .--level-1.

So, my question is: Is there a way to get inner section .--level-2 with closest()? Or what's the better way to solve this issue?

const el = document.getElementById('target');

const r1 = el.closest(".container--expanded");

const r2= el.closest(".container--expanded .section");
console.log('r1', r1);
console.log('r2', r2); //expect to get <div class="section --level-2">
.container--expanded {
  width: 600px;
  height: auto;
  background-color: grey;
 }
 
.container--expanded.--level-2 {
  background-color: yellow;
}


.section {
  width: 400px;
  height: 80px;
  border: 4px solid black;
}

.section.--level-2 {
  border: 4px solid red;
}
<div class="container--expanded">
  <span>Span 1</span>
  <div class="section --level-1">
    <p>Level 1</p>

    <div class="container--expanded --level-2">
       <span id="target">Span 2</span>
       <div class="section --level-2">
         <p>Level 2</p>
       </div>
    </div>

  </div>
</div>

Also, I've added it on codepen: https://codepen.io/wilchilly/pen/GRMyYLB?editors=1111

Would be really grateful for any help!

MarkMark
  • 174
  • 1
  • 11
  • _"The `closest()` method **traverses the Element and its parents (heading toward the document root)** until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns `null`."_ - The answer to _"Is there a way to get inner section .--level-2 with closest()?"_ would therefor be "No" – Andreas Dec 28 '21 at 14:38
  • Related, same cause: [Why does querySelector('div span') match even though querySelector('div') does not?](/q/64522987/4642212) and [queryselectorAll with descendant not selecting correctly](/q/49545252/4642212). – Sebastian Simon Dec 28 '21 at 14:38
  • 1
    If you know that the `--level-` elements are nested within the `.container--expanded` elements, why not simply combine `closest()` and `querySelector()`, to give: `const r2= el.closest('.container--expanded').querySelector('.section');` – David Thomas Dec 28 '21 at 14:43

0 Answers0