简体   繁体   中英

OnClick Hide Div with Pure JavaScript for Notification bar

I am creating a notification bar with a close button. I am using the below code.

 document.getElementById("close").onclick = function() { var d = document.getElementsByTagName("div"); for (var i = 0; i < d.length; i++) { d[i].style.display = 'none'; } }
 <div id="top-bar"> <p> Dummy Text  <a class="button light" href="#" target="_blank" rel="noopener opener noreferrer">Get Now</a><button id="close" href="#">X</button> </p> </div>

The code is working fine, it closes the div but the problem is my whole site gets blank after clicking the close button.

You are getting all the "div" elements here:

var d = document.getElementsByTagName("div");

Change it for something like:

var d = document.getElementById("top-bar");

With getElementById, you now will be getting just one element, so the "for" is not required:

document.getElementById("close").onclick = function() {
  var d = document.getElementById("top-bar");
  d.style.display = 'none';
}

I would recommend to add type="button" to your "button" tag and remove href attribute as this is not an "a" tag.

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