Reputation: 285
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?
Upvotes: 1
Views: 393
Reputation: 165941
When your script runs, the foo
element doesn't exist. If you check the JavaScript console you should see an error, along the lines of this:
Uncaught TypeError: Cannot read property 'firstChild' of null
You get this error because getElementById
will return null
if the element you're looking for isn't found.
You need to execute the JavaScript code after the markup. Move your script
tag to the bottom of the body
, or put it in a DOM ready/load event handler. For example:
<body onload="alert(theText)">
<a id="foo" href="old">Foobar</a>
<!-- Now the `foo` element actually exists, our script can find it -->
<script type="text/javascript">
var theText = document.getElementById('foo').firstChild.nodeValue;
</script>
</body>
Upvotes: 1