+ 1
JavaScript getElementById keeps returning null
JavaScript getElementById keeps returning null whether I map colorInp to the element itself or the value... Anybody know why SoloLearn doesn't accept getElementById? " <input type='text' id='color'/> var colorInp = document.getElementById('color').value; console.log(colorInp); "
7 Answers
+ 9
Did you add a load event such as onload to wrap your statements?
onload = function () {
var colorInp = document.getElementById('color').value;
console.log(colorInp);
}
... of course this code, as it is, won't print anything because the text field is empty, maybe you would prefer to attach an event listener such as ".oninput" on.
[EDIT] Glad you fixed it, as a further reference: https://code.sololearn.com/WLA0GC87jhzx/?ref=app
+ 11
@Dustin i added a demo (edited answer), if you feel stuck, just look at it and check whether it is the solution you're looking for.
Good luck! ;P
+ 3
you can use this also short and easy
<input type='text' id='color' onkeyup="ck()"/>
<p id="p"></p>
<script>
function ck() {
var colorInp = document.getElementById('color').value;
p.innerHTML =colorInp;
}
</script>
+ 1
I like this
0
I forgot to wrap with the onload function, but in my actual code I added the "change" event, but it won't even capture the element itself, just keeps returning null
0
Ok, I feel retarded.... It was the fact that I didn't wrap it with the onload function. Thanks @maz, all good now!
0
not sure what event I'm gonna use for this particular one, biggest concern was having the browser at least capture the element itself before adding any event listeners