Why does `document.getElementById(“#sideNav”)` not find my element?

a 夏天 提交于 2021-02-05 12:28:34

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/38479889/why-does-document-getelementbyidsidenav-not-find-my-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!