SitePoint Sponsor |
|
User Tag List
Results 1 to 3 of 3
Thread: document.getElementById
-
Jun 30, 2008, 03:02 #1
- Join Date
- Jun 2008
- Posts
- 49
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
document.getElementById
Hello,
I'd like to ask you, why doesn't this work:
<html>
<head>
<title>getElementById example</title>
<script type="text/javascript">
var target = document.getElementById("para1");
alert(target.nodeName);
</script>
</head>
<body>
<p id="para1">Some text here</p>
</body>
</html>
It says that "target is null". But I don't know why. Can anyone help? Thanks.Last edited by jake.polak; Jun 30, 2008 at 06:12.
-
Jun 30, 2008, 03:42 #2
- Join Date
- Aug 2004
- Location
- Manchester UK
- Posts
- 13,807
- Mentioned
- 158 Post(s)
- Tagged
- 3 Thread(s)
It's because the element you are referencing hasnt been created when you call for it.
Code:<html> <head> <title>getElementById example</title> </head> <body> <div id="para1">Some text here</div> <script type="text/javascript"> var target = document.getElementById("para1"); alert(target.nodeName); </script> </body> </html>
Mike Swiffin - Community Team Advisor
Only a woman can read between the lines of a one word answer.....
-
Jun 30, 2008, 04:56 #3
If you want to keep the script in the head of your HTML page then you can wrap the code in a function assigned to the onload event handler of the window:
Code:<html> <head> <title>getElementById example</title> <script type="text/javascript"> window.onload = function() { var target = document.getElementById("para1"); alert(target.nodeName); } </script> </head> <body> <div id="para1">Some text here</div> </body> </html>
Coding and design philosophy:
Keep It Simple, Stoopid
Bookmarks