Access this property on a variable that is not actually an element
For example, you have an array of HTML Elements. It contains 2 elements, but then you access the property of the third element in the array:
// You have array of two HTML elements const head = document.head const body = document.body const array = [head, body] // Then you access the third element property ‘style’ console.log(array.style)
The error will be raised because, as we have said, you are accessing the property of something which is called undefined, not an HTML Element anymore. If you may probably want to access the second element, you can read the solutions in the next section to see how to solve it.
You are declaring the HTML Element after reading the property
One common cause of this error is that you have been accessing the property ‘style’ before that element is created. This would happen when you put your script in the head tag instead of the last line of the body tag. For example:
How to fix this error?
Check the type of the element before reading property
As we have explained, maybe you have accessed an out-of-bound array element. You should check the index to see if it is smaller than the array length and is at least 0 or not.
// You have array of two HTML elements const head = document.head const body = document.body const array = [head,body] // Then you access the second element property ‘style’ console.log(array.style)
Or if it is not an array element that has invalid index, it may be an element returned by the GetElementBy functions, but the name or id you passed into it does not exist. In this case, please check the name in the parameter of that function again and make sure to pay attention to the case-sensitive. Because using a function with a misspelled name may cause this error. Therefore, we also suggest you check the function name again, which is assigned to the object you are reading property.
Declare the element first before reading property
This is the solution to the second cause in this tutorial. All you have to do is putting the script tag at the end of your body tag so it will be executed last.
Maybe you are interested:
- Cannot read property ‘addeventlistener’ of null in js
Name of the university: HCMUT