[JS] Why does document.getElementById("myId") return null | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

11th Feb 2017, 1:28 AM
Pete Wright
Pete Wright - avatar
9 Answers
+ 9
<span id="myId">Hello</span> alert(document.getElementById("myId").innerText) will output "Hello"
11th Feb 2017, 6:40 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 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.
11th Feb 2017, 7:09 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 6
Then just put window.onload what's so off-topic about that? Was I talking about Mario Kart?
11th Feb 2017, 7:53 AM
David Sebastian Keshvi Illiakis
David Sebastian Keshvi Illiakis - avatar
+ 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.
11th Feb 2017, 4:48 AM
visph
visph - avatar
+ 2
@Cheeze: Off topic ^^
11th Feb 2017, 7:04 AM
visph
visph - avatar
+ 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...
11th Feb 2017, 7:17 AM
visph
visph - avatar
+ 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
11th Feb 2017, 2:24 AM
Pete Wright
Pete Wright - avatar
0
This code alerts 'null' too alert(document.getElementById("myId"));
11th Feb 2017, 1:36 AM
Pete Wright
Pete Wright - avatar
0
This works, I just tried it...
11th Feb 2017, 2:19 AM
Dawzy
Dawzy - avatar