Cannot read property null javascript

Error: Cannot read property ‘value’ of null

I am extremely new to javascript and so I apologize in advance for any problems with the way I am asking my quesion. I am trying to post data and have a warning pop up if all fields are not filled out. And one of the fields is a radio type. Here is a link to a jsfiddle with my script http://jsfiddle.net/J2yWQ/64/ Here is what I have at the moment

function emailWarning() < var check = document.getElementById("check"); check.className = 'show'; >function validateEmail(xem) < var re = /\S+@\S+\.\S+/; return re.test(xem); >function postData() < email = 'email'+document.getElementById('email').value; var tt = validateEmail(email); if (tt == true) < xmlhttp.open('POST', 'payment.php', true); xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlhttp.send(myProps.join("&")); >else < emailWarning(); >> function insert() < try < if (window.XMLHttpRequest) < xmlhttp = new XMLHttpRequest(); >else < xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); >var myProps = []; function addProp(id) < var value = encodeURIComponent(document.getElementById(id).value); myProps.push(id + "=" + value); >addProp('child_name'); addProp('age'); addProp('hometown'); addProp('boy_girl'); addProp('first_name'); addProp('last_name'); addProp('email'); addProp('address1'); addProp('address2'); addProp('city'); addProp('state'); addProp('zip'); addProp('country'); var flagInvalid = false; var tempArray = document.getElementsByClassName("required"); for (var i = 0; i < tempArray.length; i++) < if (tempArray[i].value == "") < flagInvalid = true; break; >> if (flagInvalid == false) < postData(); >else < var log = document.getElementById("log"); log.className = 'show'; var log1 = document.getElementById("log1"); log1.className = 'show'; var log2 = document.getElementById("log2"); log2.className = 'show'; var log3 = document.getElementById("log3"); log3.className = 'show'; var log4 = document.getElementById("log4"); log4.className = 'show'; var log5 = document.getElementById("log5"); log5.className = 'show'; var log6 = document.getElementById("log6"); log6.className = 'show'; var log7 = document.getElementById("log7"); log7.className = 'show'; var log8 = document.getElementById("log8"); log8.className = 'show'; var log9 = document.getElementById("log9"); log9.className = 'show'; var log0 = document.getElementById("log0"); log0.className = 'show'; var logA = document.getElementById("logA"); logA.className = 'show'; >> catch (e) < alert('An error occured in inert: ' + e); >> 

It doesn’t say which line. The «catch» is catching it because I am getting the text ‘ An error occurred in inert: . ‘

Читайте также:  Porto e commerce html template

@nja — those are the IDs in spans that are hidden and become shown (or should) when a field is left blank.

It happens here:function addProp(id) < Unhandled Error: Cannot convert 'document.getElementById(id)' to object var value = encodeURIComponent(document.getElementById(id).value); myProps.push(id + "=" + value);

Источник

Почему возникает ошибка: Uncaught TypeError: Cannot read property of undefined or null (reading ***)

Периодически, при разработке на JavaScript возникает ошибка: Cannot read property *** of undefined или Cannot read property *** of null Например в этом коде:

const count = result.data.length; 
const dataMap = response.lines.map(item => item * 2); 

1 ответ 1

Cannot read property of undefined/null (reading ‘method’)

Ошибка нам говорит, что мы пытаемся вызвать свойство или метод method объекта, в то время, как сам объект являет null или undefined

Рассматривать будем на примере данного объекта

Ошибка возникнет, если мы попытаемся выполнить следующий код:

data.errors.forEach(item => console.log(item)); // null.forEach() 

Uncaught TypeError: Cannot read properties of null (reading ‘forEach’)

data.values.map(item => console.log(item)); // undefined.map() 

Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)

Данные ошибки говорят нам о том, что мы пытаемся вызвать методы у ничего(null или undefined).
data.errors это null. У null нет методов. А data.values вообще не существует. Нельзя вызвать метод у того, что не существует.

Так же, если объявить переменную и попытаться вызвать у нее какой либо метод без инициализации, то получим ошибку(в данном случае Cannot read properties of undefined (reading ‘push’)):

const arr; arr.push(1); // undefined.push(); 

Cannot read property

of undefined — ключ не определен, т.е. отсутствует в объекте.
of null — ключ в объекте есть, но имеет значение null. У null нет методов.

Как понять, где возникла ошибка?

file:///C:/dev/nodeserver/SO/11.js:10 // Номер строки data.errors.forEach(item => console.log(item)); // null.forEach() ^ TypeError: Cannot read properties of null (reading 'forEach') at ←[90mfile:///C:/dev/nodeserver/SO/←[39m11.js:10:13 ←[90m at ModuleJob.run (node:internal/modules/esm/module_job:193:25)←[39m at async Promise.all (index 0) ←[90m at async ESMLoader.import (node:internal/modules/esm/loader:533:24)←[39m ←[90m at async loadESM (node:internal/process/esm_loader:91:5)←[39m ←[90m at async handleMainPromise (node:internal/modules/run_main:65:12)←[39m 

Здесь at ←[90mfile:///C:/dev/nodeserver/SO/←[39m11.js:10:13 мы видим номер строки с ошибкой и позицию, где произошла ошибка.

В браузере это выглядит так:

Uncaught TypeError: Cannot read properties of null (reading 'forEach') at 123.html?_ijt=vkfkm1ubo3ut5c02m72ihg4lgu:72:15 

где 72 это номер строки, а 15 это точка, где возникла ошибка.

Как этого избежать?

Проверять, что приходит в объекте и существуют ли в объекте нужные нам значения. Один из вариантов проверки, воспользоваться console.log() .
Можно начать с последнего ключа, однако лучше весь пусть вывести, что бы понимать структуру, с которой работаем:

console.log(data) // < name: 'TypeError', message: '', errors: null, sayHi: [Function] >console.log(data.errors) // null 

Так же можно воспользоваться оператором необязательной цепочки вызовов ‘?.

const a = data?.errors?.forEach(item => console.log(item)); // null.forEach() const b = data?.values?.map(item => console.log(item)); // undefined.map() 

Оператор необязательной цепочки вызовов будет проверять значение слева. Если значение null или undefined , цепочка прерывается и возвращается значение undefined.

Для объявленных переменных указывать тип данных

const arr = []; // Указываем, что меременная это массив arr.push(1); // Можем воспользоваться любым методом массива; 

Источник

Uncaught TypeError: Cannot read property ‘value’ of null [duplicate]

I’m getting error in this code, I’m trying to do an event where in when the page is load, it will do the event. But the problem is when I go to other function, but same page, it gets a error of null on that variable. It has no problem when I execute this code, but when I’m on other part of my code this error occurs.

$(document).ready(function() < var str = document.getElementById("cal_preview").value; var str1 = document.getElementById("year").value; var str2 = document.getElementById("holiday").value; var str3 = document.getElementById("cal_option").value; if (str=="" && str1=="" && str2=="" && str3=="" ) < document.getElementById("calendar_preview").innerHTML=""; return; >if (window.XMLHttpRequest) else xmlhttp.onreadystatechange=function() < if (xmlhttp.readyState==4 && xmlhttp.status==200) < document.getElementById("calendar_preview").innerHTML=xmlhttp.responseText; >> var url = calendar_preview_vars.plugin_url + "?id=" + str +"&"+"y="+str1+"&"+"h="+str2+"&"+"opt="+str3; xmlhttp.open("GET",url,true); xmlhttp.send(); >); 

you sure the elements with first four ids exist? put a debugger; statement in your ready function and see which line throws error.

They do exist, it has no problem when this function is called, but when you are on other function, this is the time that it has error.

If document.getElementById can’t find an element with the supplied ID, it returns null. So the error is telling you it can’t find one of the elements by ID.

10 Answers 10

I am unsure which of them is wrong because you did not provide your HTML, but one of these does not exist:

var str = document.getElementById("cal_preview").value; var str1 = document.getElementById("year").value; var str2 = document.getElementById("holiday").value; var str3 = document.getElementById("cal_option").value; 

There is either no element with the id cal_preview , year , holiday , cal_option , or some combination.

Therefore, JavaScript is unable to read the value of something that does not exist.

If you want to check that the element exists first, you could use an if statement for each:

var str, element = document.getElementById('cal_preview'); if (element != null) < str = element.value; >else

You could obviously change the else statement if you want or have no else statement at all, but that is all about preference.

I think your getting my point, I tried to put a validation there like if null, but did not work. Is it possible to verify if value exist or not? Did I understand it correctly?

You want to just check if it exists and do nothing if it does not or try to figure out which one it thinks does not exist?

the error now is on this part document.getElementById(«calendar_preview»).innerHTML=xmlhttp.responseText;,. cannot set property innerhtml of null

Just simply do exactly the same that you did on the previous. Also, if you want, you could just skip everything if one of them does not exist.

Easier and more succinct with || :

 var str = ((document.getElementById("cal_preview")||<>).value)||""; var str1 = ((document.getElementById("year")||<>).value)||""; var str2 = ((document.getElementById("holiday")||<>).value)||""; var str3 = ((document.getElementById("cal_option")||<>).value)||""; if (str=="" && str1=="" && str2=="" && str3=="" ) < document.getElementById("calendar_preview").innerHTML=""; return; >if (window.XMLHttpRequest) else xmlhttp.onreadystatechange=function() < if (xmlhttp.readyState==4 && xmlhttp.status==200) < document.getElementById("calendar_preview").innerHTML=xmlhttp.responseText; >> var url = calendar_preview_vars.plugin_url + "?id=" + str +"&"+"y="+str1+"&"+"h="+str2+"&"+"opt="+str3; xmlhttp.open("GET",url,true); xmlhttp.send(); 

My mistake was that I was keeping the Javascript file ( tag) above the html declaration.

It worked by placing the js script tag at the bottom of the body inside the body. (I did not the script on load of the page.)

if (document.getElementById('cal_preview') != null)

If in your HTML you have an input element with a name or id with a _ like e.g. first_name or more than one _ like e.g. student_first_name and you also have the Javascript code at the bottom of your Web Page and you are sure you are doing everything else right, then those dashes could be what is messing you up.

Having id or name for your input elements resembling the below

Then you try make a call like this below in your JavaScript code

var first_name = document.getElementById("first_name").value; 
var student_first_name = document.getElementById("student_first_name").value; 

You are certainly going to have an error like Uncaught TypeError: Cannot read property ‘value’ of null in Google Chrome and on Internet Explorer too. I did not get to test that with Firefox.

In my case I removed the dashes, in first_name and renamed it to firstname and from student_first_name to studentfirstname

At the end, I was able to resolve that error with my code now looking as follows for HTML and JavaScript.

var firstname = document.getElementById("firstname").value; 
var studentfirstname = document.getElementById("studentfirstname").value; 

So if it is within your means to rename the HTML and JavaScript code with those dashes, it may help if that is what is ailing your piece of code. In my case that was what was bugging me.

Источник

Cannot read property null javascript

Last updated: Jan 3, 2023
Reading time · 2 min

banner

# Cannot read properties of null (reading ‘classList’) in JS

There are 2 reasons the «Cannot read properties of null (reading ‘classList’)» error occurs:

  1. Accessing the classList property on a null value (a DOM element that doesn’t exist).
  2. Placing the JS script tag above the HTML where the DOM elements are declared.

cannot read property classlist of null

Here is an example of how the error occurs.

Copied!
const box = document.getElementById('does-not-exist'); console.log(box); // 👉️ null // ⛔️ Uncaught TypeError: Cannot read properties of null (reading 'classList') box.classList.add('bg-green-400');

We attempted to access the classList property on a null value which caused the error.

# Make sure the DOM element exists before accessing classList

Make sure the id you’re using to get the DOM element is valid and exists in the DOM.

The error often occurs when providing an invalid id to the getElementById() method.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="box">Hellodiv> script src="index.js"> script> body> html>

The id of the DOM element should match the identifier you have passed in the call to the document.getElementById() method.

# Place the JS script tag at the bottom of the body tag

Place the JS script tag at the bottom of the body tag.

The JS script tag should run after the HTML elements have been declared.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> script src="index.js"> script> div id="box">Hellodiv> body> html>

The index.js script is run before the HTML elements have been created, so we can’t access the HTML elements in the index.js file.

Copied!
const box = document.getElementById('box'); console.log(box); // 👉️ null // ⛔️ Cannot read properties of null (reading 'classList') box.classList.add('bg-green-400');

Instead, you should place the script tag at the bottom of the body tag, after all DOM elements it needs access to.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> div id="box">Hellodiv> script src="index.js"> script> body> html>

place script tag at bottom of body tag

Now the div with id of box is accessible inside of the index.js file.

Copied!
const box = document.getElementById('box'); console.log(box); // 👉️ div#box // ✅ works box.classList.add('bg-green-400');

accessing classlist property successfully

HTML code is parsed from top to bottom, so we have to place the script tag at the bottom of the body tag, after all of the DOM elements it needs access to.

# Conclusion

The «Cannot read properties of null (reading ‘classList’)» error occurs when trying to access the classList property on a null value.

To solve the error, make sure the JS script tag is loaded after the HTML is created and the id of the element exists in the DOM.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью