0

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?

9
  • Try it with dropDownNav[0].style.display Commented May 6, 2013 at 11:02
  • Why do you pass undefined dropDownNav to toggle_visibility? Commented May 6, 2013 at 11:03
  • You also have to move var dropDownNav = document.getElementsByClassName("dropDownNav"); outside the function. Commented May 6, 2013 at 11:04
  • @thebreiflabb - why does he have to move it outside the function? Commented May 6, 2013 at 11:05
  • Never mind that actually, I saw he used dropDownNav as an argument in the onclick attribute, which would be undefined unless it was outside the function. But I can see he is not using it inside the function. Commented May 6, 2013 at 11:09

1 Answer 1

5

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.