I'm quite a beginner so apology for my question if it's dumb.
I have an unordered list and a button in HTML and I want to make the button show or hide the list via javascript, but I am trying to avoid giving the onclick
attribute to the button in the HTML
code.
var btn = document.getElementById("button");
btn.onclick = function(){
var ul = document.getElementById("ul");
if(ul.style.display=='none'){
ul.style.display='block'}
else{ul.style.display='none'}
}
<ul id=ul>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
<li>List item 5</li>
<li>List item 6</li>
</ul>
<input id="button" type="button" name="button" value="press me!" >
What am I missing here, can't make it work? Could only do it when I included the onclick
attribute in HTML
and made a showhide()
function for its onclick event, but that seems impractical in the long run.
` in your HTML, that way your script will run once all the elements have loaded, allowing your script to access them
– Nick Parsons Oct 12 '20 at 13:21