-2

Why is this code throwing TypeError: Cannot read property 'style' of null?

function openNav() {
  document.getElementById("#sideNav").style.width = "250px";
}

function closeNav() {
  document.getElementById("#sideNav").style.width = "0";
}
<div class="sidenav" id="sideNav">
  <a href="javascript:void(0)" class="closenav" onclick="closeNav()">&times;</a>
  <a href="#">Home</a>
  <a href="#">Listing</a>
  <a href="#">About Us</a>
  <a href="#">Contact</a>
</div>
<span onclick="openNav()">OPEN</span>
<div id="main">
  ...
</div>
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • Does this answer your question? [Why does \`document.getElementById(“#datepicker1”)\` not find my element?](https://stackoverflow.com/questions/33036800/why-does-document-getelementbyid-datepicker1-not-find-my-element) – Sebastian Simon Jul 06 '20 at 04:48
  • Related: [When to use the `#` symbol to get a DOM element?](https://stackoverflow.com/q/15486154/4642212). – Sebastian Simon Jul 06 '20 at 04:55

1 Answers1

8

Because getElementById takes an id, not a CSS selector. Just lose the # on those:

document.getElementById("sideNav").style.width = "250px";
// No # here ------------^

querySelector and querySelectorAll take CSS selectors, but getElementById does exactly what the name suggests: Gets an element by its ID.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875