1

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()">&times;</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";
}
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
I Like
  • 1,711
  • 2
  • 27
  • 52

3 Answers3

1

I tried to change it in the Tryit Editor and changed the line to

document.getElementsByClassName("sidenav")[0].style.width = "250px";

and it worked. Did you forget to use the index as you get an array in this case.

NilsB
  • 1,154
  • 1
  • 16
  • 42
1

When you've got something like a menu that there will only be one of on each page you should stick to ID. ID is ensured to only match one occurrence. Matching by class should be done if you've got multiple elements that should behave in the same way. If you however want to match by class, I assume you tried using getElementsByClassName("sidenav"). In thus case you must specify which match to get, since it will return an array. The correct syntax would then be getElementsByClassName("sidenav")[0]

Script_Coded
  • 709
  • 8
  • 21
1

Both selectors will work, but selecting an element by id is faster.

See this question for more info:In jQuery, is selecting by class or id faster than selecting by some other attribute?
Even though this question is about jquery, jquery uses native browser selectors (getElementById or getElementsByClassName) if available

Community
  • 1
  • 1
Buksy
  • 11,571
  • 9
  • 62
  • 69