I'm new to JavaScript and this site. I need help with trying to toggle a div's visibility, the div
is a html semantic tag ( nav
), and I can't find a way to reference it.
I have searched for a good hour and have tried document.getElementById()
, but that doesn't work unless I change the tag to <div id="nav">
.
My JavaScript code is as follows:
function toggle_visibility(id) {
"use strict";
var e = document.getElementById(id);
if (e.style.display === 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}}
And I'm calling it from another div in my html like this
<a href="#" onclick="toggle_visibility('nav');"><div id="mNav"></div></a>
<nav>
<ul>
<a href=""><li>
Link 1
</li></a>
<a href=""><li>
Link 2
</li></a>
<a href=""><li>
Link 3
</li></a>
</ul>
</nav>
In your case document.getElementById
is used only if the element has an ID. But if you want to get reference of the element using tag name, then you must use document.getElementsByTagName
. But again this would make your generic function toggle_visibility
to be limited to tagname.
Instead of both, use document.querySelector
. To this function, you can pass css selectors and it can be either id or tag name or class name as well.
function toggle_visibility(selector) { "use strict"; var e = document.querySelector(selector); e.style.display = (e.style.display==="block") ? "none" : "block"; }
<a onclick="toggle_visibility('nav');">Toggle Menu<div id="mNav"></div></a> <nav> <ul> <a href=""><li> Link 1 </li></a> <a href=""><li> Link 2 </li></a> <a href=""><li> Link 3 </li></a> </ul> </nav>
Also instead of binding the click event to the element inside the HTML, use addEventListener
to bind the event. It would be easier for you to manage.
Now in your HTML you can even reference like:
toggle_visibility("#myNav")
toggle_visibility(".className")
nav
is not id in your case, but a tag name. In this case, use:
var e = document.getElementsByTagName(id)[0];
Or, more flexible solution:
var e = document.querySelector(id);
(also, as it's not id, you probably want to replace id
parameter with tag
, but that's just cosmetic :) )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.