Solve - Cannot read Property 'add' of Undefined in JS

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

banner

Photo by Autri Taheri

Solve - Cannot read property 'add' of Undefined #

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.

index.js
const el = undefined; // โ›”๏ธ 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.

index.html
<!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.

index.js
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.

index.js
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.

index.js
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).

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee