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!