Borislav Hadzhiev
Fri Dec 24 2021·2 min read
Photo by Marc Rafanell López
The "getBoundingClientRect is not a function" error occurs for multiple reasons:
getBoundingClientRect()
method on a value that is not a DOM
element.getBoundingClientRect
(it's case sensitive).Here is an example of how the error occurs.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <!-- ✅ Your JS script here ✅ --> <script type="module" src="index.js"></script> </body> </html>
index.js
file.And here is the related JavaScript code.
const boxes = document.getElementsByClassName('box'); // ⛔️ TypeError: boxes.getBoundingClientRect is not a function const result = boxes.getBoundingClientRect();
We called the
Element.getBoundingClientRect()
method on a NodeList
and not a DOM element, so we got the error back.
To solve the "getBoundingClientRect is not a function" error, make sure to
only call the getBoundingClientRect
method on valid DOM elements and place the
JS script tag at the bottom of the body, after the DOM elements have been
declared.
const boxes = document.getElementsByClassName('box'); const result = boxes[0].getBoundingClientRect(); // 👇️ {bottom: 26.87..., height: ..., left: ..., right: ...} console.log(result);
By accessing the element at index 0
of the NodeList
, we got back a DOM
element, on which we can safely call the getBoundingClientRect
method.
getBoundingClientRect
method on it.For example, a basic DOM element has a type of object, so we can check if the
value is an object and contains the getBoundingClientRect
property before
calling the method.
const box = null; if (typeof box === 'object' && box !== null && 'getBoundingClientRect' in box) { const result = box.getBoundingClientRect(); console.log(result); }
Our if
condition uses the logical AND (&&) operator, so for the if
block to
run, all of the conditions have to be met.
box
variable stores a value with a type of object because DOM elements have a type of object.Then we check if the variable is not equal to null
. Unfortunately, if you
check the type of null - console.log(typeof null)
, you will get an "object"
value back, so we have to make sure the value is not null
.
getBoundingClientRect
property.Then we know we can safely call the getBoundingClientRect
method on the
object.
getBoundingClientRect
as it is case sensitive and quite tricky to spell.You can also console.log
the value you're calling the method on and make sure
it's a valid DOM element.