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
https://forums.phpfreaks.com/topic/196759-documentgetelementbyid/
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.
  }
};

 

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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.