0
[JS] Why does document.getElementById("myId") return null
[HTML] <span id="myId"></span> [JS] function el(e){ var e = e; e = document.getElementById(e); return e; } var x = el("myId"); alert(x); // alerts 'null' but why?
9 Answers
+ 9
<span id="myId">Hello</span>
alert(document.getElementById("myId").innerText) will output "Hello"
+ 6
@visph lol? OP is asking why does that return null and you were talking about web project code has 3 separate files html css and js who is off-topic now? Check yourself before you wreck yourself.
+ 6
Then just put window.onload what's so off-topic about that? Was I talking about Mario Kart?
+ 3
You find the answer: in web project code playground, the tree tabs html, css and js are treated as 3 separate ( vrtual ) files, css and js silently auto linked to the html in the <head> part as if you ( could ) have:
<link href="tab:css" rel="stylesheet" type="text/css"> or <style>/* css tab code */</style> for css in a 'one-file' version;
<script src="tab:js"></script> or <script>/* js tab code */</script> for js in a 'one-file' version.
+ 2
@Cheeze: Off topic ^^
+ 2
The reason of null returned, is that DOM is not ready to be accessed by JS...
So your answer doesnt help since null is returned...
And the code playground is confusing about how is linked Css and JS tab...
+ 1
nope, doesn't work.
I added following code:
window.onload = function (){
[JS code]
}
I thought the JS would run automatically AFTER the HTML is *fully* loaded
0
This code alerts 'null' too
alert(document.getElementById("myId"));
0
This works, I just tried it...