问题
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()">×</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