TypeError: Cannot read Property 'add' of Undefined in JS


Borislav Hadzhiev

Last updated: Oct 21, 2021


Photo from Unsplash

TypeError: Cannot read Property 'add' of Undefined in JS #

The cannot read property 'add' of undefined error occurs when calling the add() method on an undefined value. To solve the error, make sure to call the add() method after accessing the classList property on a valid DOM element.

cannot read property add of undefined

Here is an example of how the error occurs.

const el = undefined; // ⛔️ TypeError: Cannot read properties of undefined (reading 'add') console.log(el.add('example'));

To solve the error, make sure to call the add() method on a valid DOM element, here's an example.

<!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> <!-- ✅ GOOD - div elements already exist ✅ --> <script src="index.js"></script> </body> </html>

And here is the JS code that adds the class.

const boxes = document.getElementsByClassName('box'); console.log(boxes); // 👉️ [div.box, div.box, div.box] for (const box of boxes) { box.classList.add('new'); }
Notice that we placed the JS script tag at the bottom of the body tag. Had we placed the script above the elements, the div elements wouldn't be accessible inside the index.js file.

We used the getElementsByClassName method to get all of the DOM elements that have a class name of box.

The next step is to use the for...of loop to iterate over the array-like object and call the add() method on each element.

If you only need to use the add method on a single element, you can use the optional chaining (?.) operator.

const boxes = []; boxes?.[0]?.classList?.add('new');

The optional chaining (?.) operator allows us to short-circuit instead of throwing an error.

If the reference is equal to undefined or null, the operator returns undefined otherwise it returns the value of the property / method.

If the references are not nullish, we end up calling the add() method and adding the new class to the DOM element, otherwise we short-circuit.

Alternatively, you can also use the logical AND (&&) operator.

const boxes = []; if (boxes && boxes[0] && boxes[0].classList && boxes[0].classList.add) { boxes[0].classList.add('new'); }

The logical AND (&&) operator won't evaluate the value to the right if the value to the left is falsy (e.g undefined).

All of the values in the if condition have to be truthy for the if block to run.

The truthy values are all values that are not falsy.

The falsy values in JavaScript are: undefined, null, false, 0, "" (empty string), NaN (not a number).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.