Borislav Hadzhiev
Reading time·2 min
Photo from Unsplash
There are 2 main reasons the "Cannot read properties of undefined (reading 'top')" error occurs:
top
property on a DOM element that doesn't exist.Here is an example of how the error occurs.
const el = undefined; // ⛔️ TypeError: Cannot read properties of undefined (reading 'top') console.log(el.top);
The error most commonly occurs if you use a non-existent identifier.
Here's the HTML for the example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> </head> <body> <div id="box">Content</div> <script src="index.js"></script> </body> </html>
And here is the related JS code that tries to access a non-existent element.
const el = $('#does-not-exist'); console.log(el); // ⛔️ Cannot read properties of undefined (reading 'top') console.log(el.offset().top);
Calling the offset()
method returns an undefined
value and accessing the
top
property causes the error.
top
propertyMake sure that the DOM element you're accessing the top
property on exists.
You can also conditionally check to avoid getting the error.
const el = $('#does-not-exist'); // ✅ Using optional chaining const result1 = el?.offset()?.top; console.log(result1);
The optional chaining (?.) operator short-circuits instead of throwing an error
if the reference is equal to undefined
or null
.
Another common reason for getting the error is placing the JS script tag above the code that declares the DOM elements.
Make sure that the JS script tag is placed at the bottom of the body, after the HTML elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous" ></script> </head> <body> <div id="box">Content</div> <!-- ✅ GOOD - Script is run after div is declared ✅ --> <script src="index.js"></script> </body> </html>
Notice that we placed the index.js
script tag below the code that creates the
div
element.
If the JS script tag is placed above the code that creates the div
element,
the element wouldn't be accessible in the index.js
file.
const el = $('#box'); console.log(el); // ✅ Works console.log(el.offset().top); // 👉️ 8
When the correct identifier is provided and the JS script tag is loaded after
the element is created, we can access the top
property without getting the
error.
The "Cannot read properties of undefined (reading 'top')" error occurs when
trying to access the top
property on an undefined
value.
To solve the error, make sure to access the top
property on valid DOM elements
only.