dreamwest Posted March 28, 2010 Share Posted March 28, 2010 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 ..... Quote Link to comment Share on other sites More sharing options...
xenophobia Posted March 31, 2010 Share Posted March 31, 2010 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. } }; Quote Link to comment Share on other sites More sharing options...
KevinM1 Posted March 31, 2010 Share Posted March 31, 2010 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> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.