+ 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); "

14th Mar 2018, 6:17 PM
Dustin Hammack
Dustin Hammack - avatar
7 ответов
+ 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
14th Mar 2018, 6:23 PM
Maz
Maz - avatar
+ 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
14th Mar 2018, 6:31 PM
Maz
Maz - avatar
+ 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>
14th Mar 2018, 7:10 PM
Sudarshan Rai
Sudarshan Rai - avatar
+ 1
I like this
19th Mar 2018, 3:52 PM
程校校
程校校 - avatar
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
14th Mar 2018, 6:25 PM
Dustin Hammack
Dustin Hammack - avatar
0
Ok, I feel retarded.... It was the fact that I didn't wrap it with the onload function. Thanks @maz, all good now!
14th Mar 2018, 6:27 PM
Dustin Hammack
Dustin Hammack - avatar
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
14th Mar 2018, 6:29 PM
Dustin Hammack
Dustin Hammack - avatar