Etienne
Etienne

Reputation: 7201

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?

Upvotes: 1

Views: 3650

Answers (6)

ErVeY
ErVeY

Reputation: 1524

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

Upvotes: 0

Pointy
Pointy

Reputation: 413996

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!

Upvotes: 4

Adam Crossland
Adam Crossland

Reputation: 14213

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.

Upvotes: 1

Kangkan
Kangkan

Reputation: 15571

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?

Upvotes: 0

strager
strager

Reputation: 90062

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.

Upvotes: 4

Christian Smorra
Christian Smorra

Reputation: 1754

if you really want to hide something use

document.getElementById("MyDiv").style.display = "none"; 

Upvotes: 3

Related Questions