Can't hide my DIV with JavaScript
This is my DIV
<div id="MyDiv">
<div class="fa_close"><a href="#" onclick="hFa()"><img src="fadead/close1.jpg" /><开发者_开发百科/a></div>
<h1><i>THIS WEEK'S</i></h1>
<img src="fadead/special.jpg" alt="special" />
</div>
And I am trying to hide it like this but it does not want to work
document.getElementById("MyDiv").style.visibility = "hidden";
What am I doing wrong?
The code you provided works fine. There must be something else interfering. Test: http://jsbin.com/ilofi
Remember that document.getElementById("MyDiv")
returns undefined
if the element hasn't been loaded yet. Thus, document.getElementById("MyDiv")
is undefined
in the following case:
<script type="text/javascript">
alert(document.getElementById("MyDiv"));
</script>
<div id="MyDiv"></div>
But it's the element in the following case:
<div id="MyDiv"></div>
<script type="text/javascript">
alert(document.getElementById("MyDiv"));
</script>
Put scripts as close to the bottom of the page as possible for both this reason and for performance reasons.
You must make sure that your code runs after the browser has actually seen your markup. If you're trying to hide the element from a <script>
block in the <head>
, then the browser will not have seen the element yet so it won't find it.
Move your <script>
block to the very end of the <body>
and see what happens!
if you really want to hide something use
document.getElementById("MyDiv").style.display = "none";
Why not give it a style
with display:none
? Since this JavaScript is running in the HEAD, you clearly intend to have it be the starting condition of the DIV, but I can't think of a good reason to do it with JS instead of good old HTML and CSS.
I tested with the following HTML:
<body>
<div id="MyDiv">
<div class="fa_close"><a href="#" onclick="hFa()"><img src="fadead/close1.jpg" /></a></div>
<h1><i>THIS WEEK'S</i></h1>
<img src="fadead/special.jpg" alt="special" />
</div>
<input type="button" onClick="document.getElementById('MyDiv').style.visibility = 'hidden'; "/>
</body>
and it is working perfectly on my FF and IE8.
What is the browser you are using? Have you tried debugging?
you can always can try to use a framework like mootools or jquery this could help you a lot doing works like a lot more simple
mootools $("MyDiv").setStyle('display','none'); Demos: http://demos.mootools.net/
JQuery: $("#MyDiv").hide(); Demo http://api.jquery.com/hide/
if you want to view more http://www.ajaxrain.com
精彩评论