If somebody can help with this? What's wrong with the code :/ I'm trying to make a dropdown menu and I have problems with javascript code.
Getting this error: main.js: 9 Uncaught TypeError: Cannot read properties of undefined (reading 'add') at HTMLAnchorElement. (main.js:9)
Its says that the problem is with adding the add class on sidebarUl.classList.add('show');
const sidebarBtn = document.querySelectorAll('.sidebar-btn');
const sidebarUl = document.querySelectorAll('.sidebar-ul');
sidebarBtn.forEach((btn) =>
btn.addEventListener('click', function (e) {
const clicked = e.target;
console.log(clicked);
if (clicked) {
sidebarUl.classList.add('show');
} else {
sidebarUl.classList.remove('show');
}
})
);
.shop-sidenav {
position: fixed;
width: 20%;
height: 100%;
}
.sidebar ul {
height: 100%;
width: 100%;
}
.sidebar ul li {
line-height: 60px;
border-bottom: 1px solid var(--primary-color);
}
.sidebar ul li a {
padding-left: 2rem;
display: block;
width: 100%;
border-left: 1 px solid var(--primary-color);
}
.sidebar ul li a:hover {
color: var(--secondery-color);
}
.sidebar ul li a span {
float: right;
color: var(--secondery-color);
transition: transform 0.3s;
}
.sidebar ul li a:active span {
transform: rotate(-180deg);
}
.sidebar ul ul {
position: static;
display: none;
}
.sidebar-ul.show {
display: block;
}
.sidebar ul ul li {
border-bottom: none;
line-height: 40px;
}
.sidebar ul ul li a {
color: var(--secondery-color);
padding-left: 4rem;
}
<nav class="sidebar">
<div class="shop-sidenav">
<ul>
<li>
<a href="#" class="sidebar-btn">Bikes<span>⮟</span></a>
<ul class="sidebar-ul">
<li><a href="#">Giant</a></li>
<li><a href="#">Piaggio</a></li>
<li><a href="#">Trek</a></li>
<li><a href="#">Scoot</a></li>
<li><a href="#">Canyon</a></li>
<li><a href="#">Cube</a></li>
</ul>
</li>
<li>
<a href="#" class="sidebar-btn">Clothing <span>⮟</span></a>
<ul class="sidebar-ul">
<li><a href="#">Enduro</a></li>
<li><a href="#">Scoot</a></li>
<li><a href="#">Fox</a></li>
</ul>
</li>
<li><a href="#">Accessories</a></li>
<li>
<a href="#" class="sidebar-btn">Components<span>⮟</span></a>
<ul class="sidebar-ul">
<li><a href="#">Wheels</a></li>
<li><a href="#">Chain</a></li>
<li><a href="#">Gears</a></li>
<li><a href="#">Brakes</a></li>
<li><a href="#">Pumps</a></li>
<li><a href="#">Amortizers</a></li>
</ul>
</li>
</ul>
</div>
</nav>
CodePudding user response:
document.querySelectorAll
returns a list of nodes. So when adding class show
to sidebarUl you need to specify to which element you need to add. forEach
loop gives you an index with that you can acheive that
const sidebarBtn = document.querySelectorAll(".sidebar-btn");
const sidebarUl = document.querySelectorAll(".sidebar-ul");
sidebarBtn.forEach((btn,index) =>
btn.addEventListener("click", function (e) {
sidebarUl.forEach(ul=>{
ul.classList.remove("show")
})
sidebarUl[index].classList.add("show");
})
);