I have a menu that contains sub-items, when I click on them it pops up showing the items. I managed to open the first item, but I can't do the same with the second. I'm trying to use .nextElementSibling
for this, but I can't. What am I doing wrong ?
var dropdownBtn = document.querySelector('.menu-btn');
dropdownBtn.addEventListener('click',()=>{
var menuContent = document.querySelector('.drop_container');
menuContent.classList.toggle("show");
})
.menu-btn {
background: #e0e0e0;
padding: 10px;
margin: 5px 0px 0px 0px;
}
.menu-btn:hover {
background: #000;
color: #fff;
}
.drop_container {
display: none;
background-color: #017575;
transition: 0.3s;
opacity: 0;
}
.drop_container.show {
display: contents;
visibility: visible;
opacity: 1;
}
.drop_container > .item {
display: flex;
flex-direction: column;
margin-left: 10px;
padding: 10px 0px 0px 0px;
}
<div >
<div >One</div>
<div >
<a href="#">Contact Us</a>
<a href="#">Visit Us</a>
</div>
<div >Two</div>
<div >
<a href="#">Contact Us</a>
<a href="#">Visit Us</a>
</div>
</div>
CodePudding user response:
- Collect each
.menu-btn
in a NodeList, then run that through with.forEach()
. - On each iteration reference the
menuContent
asthis.nextElementSibling
. this
is the.menu-btn
that user clicked, in order to usethis
do not use an arrow function. If you prefer an arrow function, use the equivalent (in this situation)e.target
in place ofthis
.
const dropdownBtn = document.querySelectorAll('.menu-btn');
dropdownBtn.forEach(btn => btn.addEventListener('click', function() {
const menuContent = this.nextElementSibling;
menuContent.classList.toggle("show");
}));
.menu-btn {
background: #e0e0e0;
padding: 10px;
margin: 5px 0px 0px 0px;
}
.menu-btn:hover {
background: #000;
color: #fff;
}
.drop_container {
display: none;
background-color: #017575;
transition: 0.3s;
opacity: 0;
}
.drop_container.show {
display: contents;
visibility: visible;
opacity: 1;
}
.drop_container>.item {
display: flex;
flex-direction: column;
margin-left: 10px;
padding: 10px 0px 0px 0px;
}
<div >
<div >One</div>
<div >
<a href="#">Contact Us</a>
<a href="#">Visit Us</a>
</div>
<div >Two</div>
<div >
<a href="#">Contact Us</a>
<a href="#">Visit Us</a>
</div>
</div>