user2354357
user2354357

Reputation: 23

JavaScript - variable not defined

I am trying to figure out what was wrong with this code:

function toggle_visibility() {
    var dropDownNav = document.getElementsByClassName("dropDownNav");
    if (dropDownNav.style.display == 'block') e.style.display = 'none';
    else dropDownNav.style.display = 'block';
}

The HTML goes like this:

 <a class="dropDownNavButton" href="#" onclick=
"toggle_visibility(dropDownNav)"><img alt="menu icon" src=
"img/navIcon.png"></a>

<ul class="dropDownNav">
    <li class="liWorks">
        <a href="works.html">Works</a>
    </li>

    <li class="liAbout">
        <a href="#">About</a>
    </li>

    <li class="liContact">
        <a href="contact.html">Contact</a>
    </li>

    <li class="liBlog">
        <a href="#">Blog</a>
    </li>
</ul>

And yet Chrome tells me: Uncaught ReferenceError: dropDownNav is not defined onclick

Could anybody show me the way?


Thanks alot for all the quick answers! First time using stackoverflow, definitely not the last. It finally worked, I added the index[0] for the array, and removed dropDownNav on the onClick function. The only problem is, I would like the dropDownNav display to go back to none when I click on the a second time. Any clue?

Upvotes: 0

Views: 1162

Answers (1)

c.P.u1
c.P.u1

Reputation: 17084

document.getElementsByClassName() returns an HTMLCollection(similar to an array) of all elements matching the class name. The style property is not defined for HTMLCollection but for Element. Get the first element from the array using

var dropDownNav = document.getElementsByClassName("dropDownNav")[0];

Upvotes: 5

Related Questions