Uncaught TypeError: Cannot set property 'value' of null | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Uncaught TypeError: Cannot set property 'value' of null

Hey all, I'm a beginner at HTML and I'm getting an error in my code (the error above). I'm wondering why that's happening and how I can fix it: So my HTML's code snippet: <th id="discr"></th> My errors is on this line: (a b and c are inputs in from the user) discriminant = b * b - 4 * a * c; document.getElementById('discr').value = discriminant;

16th Apr 2018, 1:25 AM
Daniel Zhang
Daniel Zhang - avatar
2 Answers
+ 4
1) Wait until DOM has fully loaded (use onload etc) 2) It's .innerHTML not .value https://code.sololearn.com/WkcgllteX7JV/?ref=app
16th Apr 2018, 1:56 AM
Emma
0
In JavaScript almost everything is an object, null and undefined are exception. When you try to access an undefined variable it always returns undefined and we cannot get or set any property of undefined. In that case, an application will throw Uncaught TypeError cannot set property of undefined. In most cases, you are missing the initialization . So, you need to initialize the variable first. Moreover, if you are not sure a variable that will always have some value, the best practice is to check the value of variables for null or undefined before using them. If you just want to check whether there's any value, you can do: if( value ) { //do something } Or, if you do not know whether a variable exists (that means, if it was declared) you should check with the typeof operator . if ( typeof(some_variable) !== "undefined" && some_variable !== null ) { //deal with value } http://net-informations.com/js/err/set.htm
27th Apr 2020, 5:24 AM
rahul kumar
rahul kumar - avatar