I am currently experimenting with dropdown menus from W3Schools and have encountered an issue when trying to implement two dropdown options. The code works fine for a single dropdown, but when I try to add a second one using GetElementsByClassName instead of GetElementById, it doesn't function as expected. Here is the link to the problematic code.
code.html
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn" onclick="myFunction()">Dropdown1</a>
<div class="dropdown-content myDropdown">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</li>
<li class="dropdown">
<a href="javascript:void(0)" class="dropbtn" onclick="myFunction()">Dropdown2</a>
<div class="dropdown-content myDropdown">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</li>
function myFunction() {
document.getElementsByClassName("myDropdown").classList.toggle("show");
}
window.onclick = function(e) {
if (!e.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
for (var d = 0; d < dropdowns.length; d++) {
var openDropdown = dropdowns[d];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}