Forum Moderators: open
Below is the script and I want to make it work the way
it does below but from an external file linked from the head.
<html>
<head>
<title>Test 1</title>
</head>
<body><div id="content">
<p>Hello World</p>
</div><script type="text/javascript">
if (! document.getElementById("content")) {alert ("undefined");}
else {alert ("Defined");}
</script></body>
</html>
How I want the HTML file to look afterwards of course...
<html>
<head>
<title>Test 2</title>
<script src="script.js" type="text/javascript">
</head><body>
<div id="content">
<p>Hello World</p>
</div></body>
</html>
(follows previous from unedited original)
You'e executing inline as opposed to a function. Did you try moving the script to the bottom, just before the closing body tag?
Remember pages load from top to bottom, and "content" is not yet defined when it gets to your js. I like putting my JS at the bottom whenever I can just to move the content higher to the top.
function findContent()
{
if (! document.getElementById("content")) {alert ("undefined");}
else {alert ("Defined");}
}
<html>
<head>
<title>Test 2</title>
<script src="script.js" type="text/javascript">
</head><body onload="findContent();">
<div id="content">
<p>Hello World</p>
</div></body>
</html>
Fotiman thanks! I had the basic idea (the online but not the function aspect) but was not sure how to execute it.