+ 2

Using document.getElementById() in an Object

Why does this code return null? var doc = { car: document.getElementById('car') } doc.car.value="hello" // doesnt work doc.car.innerHtml="hello" // doesnt work it says it can not set the innerhtml of null help?

22nd Sep 2017, 11:16 PM
Sploit
Sploit - avatar
11 Answers
+ 3
It's innerHTML, not innerHtml Other then this error, your code should be working, check out the code below: https://code.sololearn.com/W34Z6SMqWnnE/?ref=app
23rd Sep 2017, 1:00 AM
CalviŐ˛
CalviŐ˛ - avatar
+ 4
In this case doc.car was null and most probably it's due to missing element of ID "car" in the DOM. 😉
23rd Sep 2017, 12:19 AM
Zephyr Koo
Zephyr Koo - avatar
+ 3
That's because it's not called by any function.. ...just wrap it up in window.onload = function(){ //put your code here! }; Note: if it's an <input> tag use ".value" else use ".innerHTML".
23rd Sep 2017, 12:20 AM
Nomeh Uchenna Gabriel
Nomeh Uchenna Gabriel - avatar
+ 3
You must to have an html tag with id="car"
23rd Sep 2017, 12:44 AM
Daniel
Daniel - avatar
+ 3
share your code
23rd Sep 2017, 12:51 AM
Daniel
Daniel - avatar
+ 2
I have an html tag with the id , I was coding it on the code playground so not sure if that makes a difference I will try the onload function
23rd Sep 2017, 12:50 AM
Sploit
Sploit - avatar
+ 2
I restarted my code right now , im going to rewrite it but using the same idea of objects within objects and using an object to target dom elements .. gonna do it on a smaller project and share the code give me about 30 minutes as my phone is dying
23rd Sep 2017, 12:54 AM
Sploit
Sploit - avatar
+ 1
I see but I got the error of it being Null even if i wrote it correctly.. I'm going to try the onload event
23rd Sep 2017, 1:02 AM
Sploit
Sploit - avatar
+ 1
onload event didn't work.. seems I can only target an element on the dom through the script tag in the html?
23rd Sep 2017, 3:23 AM
Sploit
Sploit - avatar
+ 1
I did var x; window.onload = function(){ x=document.getElementById("car"); } x.innerHTML="Vroom"; but "x" is null according to the error message
23rd Sep 2017, 3:26 AM
Sploit
Sploit - avatar
+ 1
You need to access x inside onload function. Direct access innerHTML can create error since DOM element has not been loaded yet. Please note that the code in JS pane is put inside head tag, it run before DOM elements are loaded. https://code.sololearn.com/W5eeC46RQGm1/?ref=app
23rd Sep 2017, 3:29 AM
CalviŐ˛
CalviŐ˛ - avatar