Reputation: 29
I'm relatively new to JavaScript so I'm sure this is just something I overlooked. Here's my code:
<a class="shop nav" href="#" onclick="shopBar()">Shop</a>
<div class="nav__menu">
<a class="buy__list" href="#">Shop Stuff</a>
<a class="buy__list" href="#">Shop Stuff</a>
<a class="buy__list" href="#">Shop Stuff</a>
<a class="buy__list" href="#">Shop Stuff</a>
</div>
<style>
.nav__menu {
display: none;
}
</style>
<script>
function shopBar() {
var x = document.getElementById("nav__menu");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
When I click on the a
tag, I get the error:
Uncaught TypeError: Cannot read property 'style' of null
at shopBar (index.html:63)
at HTMLAnchorElement.onclick (VM495 index.html:20)
Thanks for any help you can provide :)
Upvotes: 2
Views: 76
Reputation: 1584
The short answer, use <div id="nav__menu">
instead of <div class="nav__menu">
.
Let me give you more details about this. There are two main ways of naming elements in HTML: using a class
or id
. The difference between the two is that id
is unique. You can only have one element with the same id
. For a class
, you can have as much as you want.
So for your case, your code should be
function shopBar() {
var x = document.getElementById("nav__menu");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
.nav__menu {
display: none;
}
<a class="shop nav" href="#" onclick="shopBar()">Shop</a>
<div id="nav__menu">
<a class="buy__list" href="#">Shop Stuff</a>
<a class="buy__list" href="#">Shop Stuff</a>
<a class="buy__list" href="#">Shop Stuff</a>
<a class="buy__list" href="#">Shop Stuff</a>
</div>
Upvotes: 0
Reputation: 961
The only way for this to happen if for x to have the value null
, which means that there is no element with the id nav__menu
. The problem is that the element has the class nav__menu
, not the id nav__menu
. Switch the class to id, and you won't have a problem.
Upvotes: 0
Reputation: 191
You're using document.getElementById() but trying to target the element via its class name. To target an element by classname, use document.getElementsByClassName() (see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName)
Upvotes: 4
Reputation: 8034
You are trying to get an element by id, however no such element has this id, an so getElementWithId returns null, which explains the error
<div class="nav__menu"> // change class here to id for your code to work
Upvotes: 2