+ 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?
11 Respostas
+ 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
+ 4
In this case doc.car was null and most probably it's due to missing element of ID "car" in the DOM. 😉
+ 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".
+ 3
You must to have an html tag with id="car"
+ 3
share your code
+ 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
+ 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
+ 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
+ 1
onload event didn't work.. seems I can only target an element on the dom through the script tag in the html?
+ 1
I did
var x;
window.onload = function(){
x=document.getElementById("car");
}
x.innerHTML="Vroom";
but "x" is null according to the error message
+ 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