Borislav Hadzhiev
Thu Oct 21 2021·2 min read
Photo by Kevin Lee
The "Cannot read property 'scrollHeight' of undefined" error occurs for 2 reasons:
scrollHeight
property on an undefined
value (a DOM element
that doesn't exist).Here is an example of how the error occurs.
const elements = []; // ⛔️ cannot read property 'scrollHeight' of undefined const height = elements[0].scrollHeight;
To solve the "Cannot read property 'scrollHeight of undefined" error make sure
you're accessing the property on an existing DOM element. The error often occurs
when accessing an array index out of bounds after calling the
getElementsByClassName
method.
const elements = document.getElementsByClassName('does-not-exist'); console.log(elements); // 👉️ [] // ⛔️ cannot read property 'scrollHeight' of undefined const scrollHeight = elements[0].scrollHeight;
We provided an invalid class name to the getElementsByClassName
method, so the
method returned an empty array-like object.
Accessing the array at an index that doesn't exist returns an undefined
value.
If you then access the scrollHeight
on an undefined
value, the error is
thrown.
To solve the "Cannot read property 'scrollHeight' of undefined" error, place the JS script tag at the bottom of the body tag. The JS script should run after the DOM elements have been created.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script is ran before div exists ⛔️ --> <script src="index.js"></script> <div class="box">Hello</div> </body> </html>
Notice that we inserted the JS script tag above the HTML code that creates the
DOM elements. This means that the div
element will not be accessible inside
the index.js
file.
const elements = document.getElementsByClassName('box'); console.log(elements); // 👉️ [] // ⛔️ cannot read property 'scrollHeight' of undefined const scrollHeight = elements[0].scrollHeight;
You should place the JS script tag at the bottom of the body tag, after the HTML elements it needs to access have been created.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Hello</div> <!-- ✅ GOOD - div already exists ✅ --> <script src="index.js"></script> </body> </html>
Now we can access the div
element inside of the index.js
file.
const elements = document.getElementsByClassName('box'); console.log(elements); // 👉️ [div.box] // ✅ Works const scrollHeight = elements[0].scrollHeight; console.log(scrollHeight); // 👉️ 18
scrollHeight
property rounds the value to an integer. If you need a fractional value, use the getBoundingClientRect()
method instead.The "Cannot read property 'scrollHeight' of undefined" error occurs when the
scrollHeight
property is accessed on an undefined
value, e.g. array index
out of bounds.
To solve the error, make sure to only access the scrollHeight
property on
valid HTML elements.