简体   繁体   中英

Problem with document.getElementById in JavaScript

I am trying to display a certain div depending on what day of the week it is with JavaScript. I have a div with an id of "thu". In the JavaScript code I try to pull that id from the document but nothing happens. Here's what I have:

Here is the div, while the separate style sheet displays it as "none".

<div id="thu">Thursday</div>

Here is the JavaScript in the head section of the same page.

var date = new Date();
var dayNum = date.getDay();
switch (dayNum)
{
case 4:
document.getElementById('thu').style.display='block';   
break;

It won't display the div. I also tried assigning the element to a variable like this...

var block = document.getElementById("thu");
document.write(block);

...but it wrote "NULL".

Am I missing something? any help would be great.

Is the code running before the HTML has been written to the page? That is, is the <script> block before the <div id="thu"> ? That seems like the most likely problem.

You're probably attempting to access the element before the DOM is fully loaded. Put the call in the body Onload event, or better yet, take a look at JQuery - the way all this is handled there is very elegant.

The second block would write null if the element wasn't found. If it was found you'd get a response along the lines of [object HTMLDivElement]

You need to wait until the DOM is ready or the window has fully loaded before you can interact with it. To do that, you'll need to wrap your code in this format:

window.onload = function() {
    // put your code in here
};

When I add a closing brace } after the break , it works for me.

<div id="thu" style="display:none">Thursday</div>
<script type="text/javascript">
var date = new Date();
var dayNum = date.getDay();
switch (dayNum)
{
  case 4:
    document.getElementById('thu').style.display='block';   
  break;
}
</script>

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