简体   繁体   中英

Changing a page element's style with javascript using the <a> tag and onclick?

I have a div block

<div id='block'> <a href="#" onclick="Document.getElementById('block').style = 'display: none;';">Hide</a> </div>

and I want to be have a link that will hide the block when clicked, I tried the above but it doesn't work I'm not sure how to get this to work, any ideas or guidance?

style is an object which properties are assigned directly. It's not like the HTML attribute. So what you want is:

document.getElementById('block').style.display = 'none';
<div id='block'>  <a href="#" onclick="Document.getElementById('block').style.display = 'none';">Hide</a>  </div>

...or with some help from jquery:

$('#block').hide();
// or:
$('#block').css('display','none');

It is better to put the javascript in the <head> or better yet a separate file not the HTML. But since you have it in the HTML you could shorten your code to onclick="this.parentNode.style.display='none';"

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