Jump to content

document.getElementById()


dreamwest

Recommended Posts

Im trying to get this small javascript to work

 

  
<script>

var loc = document.getElementById("test");
  
  if(loc == true){
  
  document.write("check");
  return; 
  }
</script>

<div id="test"></div>
  

 

So basically when the page loads and if theres a div called "test" the javascropt will write "check". But ive still got it wrong .....

Link to comment
Share on other sites

The variable loc will never return you a 'true' value.

Beside, from your code, loc will always return you a null value because the element was inserted after the script. You need to check when the page was fully loaded. Try this:

window.onload = function() {
  var loc = document.getElementById('test')
  if (loc !== null) {
    // It is not empty, do whatever you want here.
  }
};

 

Link to comment
Share on other sites

Even simpler, you can put your script at the very bottom of your markup:

 

<!DOCTYPE html>
<html>
   <head></head>

   <body>
      <div id="test"></div>
   </body>

   <script type="text/javascript">
      var test = document.getElementById('test');

      if (test) { alert('check'); }
      else { alert('error'); }
   </script>

</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.