简体   繁体   中英

How to show/hide a div in javascript?

When i click the button i want the div to show, and when i click the button again i want it to disappear. What am i doing wrong?

 <button type="button" onclick="myFunction()">Click Me!</button> <div id="Dglow" class="Dglow"> Glow </div> <script> function myFunction() { var e = document.getElementById("Dglow").style.display; if (e == "none") e = "block"; else { e = "none"; } } 

You should compare and change element's display property:

 function myFunction() { var e = document.getElementById("Dglow").style; if (e.display == "none") { e.display = "block"; } else { e.display = "none"; } } 
 <button type="button" onclick="myFunction()">Click Me!</button> <div id="Dglow" class="Dglow">Glow</div> 

Actually document.getElementById("Dglow").style.display returns a string and according to Left hand assignment rule you cannot store anything to that string, since that string is not a variable/object now ie not a reference to DOM anymore

You can do is

var e = document.getElementById("Dglow").style;
if(e.display == "none")
   e.display = "block";
else{
   e.display = "none";
}

Have you considered using Jquery? If so heres what you need.

$(document).ready(function(){
    $("#button").click(function(){
        $("#Dglow").toggle();
    });
});

You would need to give your button an id for this though.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM