I was reviewing an example side navigation bar on W3Schools and had trouble understanding how the Javascript was implemented. The js is meant to open the side navigation menu via clicking a button. In the code below, why do you need to add the id mySidenav
to the menu div? I thought it would make sense to target the div via its class sidenav
with getElementsByClassName
, but that did nothing. Can someone explain why the id
is needed? I would appreciate any help as I learn js.
This is the basic html for the menu:
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()">×</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Clients</a>
<a href="#">Contact</a>
</div>
Here is the CSS for the menu:
.sidenav {
height: 100%;
width: 0;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #111;
overflow-x: hidden;
transition: 0.5s;
padding-top: 60px;
}
And the JS:
function openNav() {
document.getElementById("mySidenav").style.width = "250px";
}