I’m having trouble setting a variable and can’t find any helpful documentation.
This works:
<!DOCTYPE html>
<html>
<body onload="alert(document.getElementById('foo').firstChild.nodeValue)">
<a id="foo" href="old">Foobar</a>
</body>
</html>
But this does not work:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var theText = document.getElementById('foo').firstChild.nodeValue ;
</script>
</head>
<body onload="alert(theText)">
<a id="foo" href="old">Foobar</a>
</body>
</html>
The alert says “undefined”. What I really want to do is something like this, which also does not work:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var theElement = document.getElementById('foo') ;
var theText = theElement.firstChild.nodeValue ;
document.write(theElement.getAttribute('href')) ;
theElement.setAttribute('href', theText) ;
document.write(meta.getAttribute('href')) ;
</script>
</head>
<body>
<a id="foo" href="old">Foobar</a>
</body>
</html>
Why is this not working?
When your script runs, the
fooelement doesn’t exist. If you check the JavaScript console you should see an error, along the lines of this:You get this error because
getElementByIdwill returnnullif the element you’re looking for isn’t found.You need to execute the JavaScript code after the markup. Move your
scripttag to the bottom of thebody, or put it in a DOM ready/load event handler. For example: