Solve - Cannot set property 'color' of Undefined in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - Cannot set property 'color' of Undefined #

The "Cannot set property 'color' of undefined" error occurs when setting a property on an undefined value. To solve the error, conditionally check if the value is of the expected type (object or array) or has to be initialized before setting the property on it.

cannot set property color of undefined

Here's an example of how the error occurs.

index.js
const element = undefined; // โ›”๏ธ Cannot set properties of undefined (setting 'color') element.color = 'green';

The error most commonly occurs when trying to set the color of a DOM element after using the getElementsByClassName method. The getElementsByClassName method returns an array-like object that contains the selected elements, so you should access an element at a specific array index.

Here's the HTML for a working example

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Content 1</div> <div class="box">Content 2</div> <div class="box">Content 3</div> <!-- โœ… Script is ran after div elements are created โœ… --> <script src="index.js"></script> </body> </html>

And here's the related JS code.

index.js
const elements = document.getElementsByClassName('box'); console.log(elements); // ๐Ÿ‘‰๏ธ [div.box, div.box, div.box] // โœ… Change color of first element with class elements[0].style.color = 'green'; // โœ… Change color of all elements with class for (const element of elements) { element.style.color = 'green'; }

We used the getElementsByClassName to get an array-like object containing all the DOM elements with a class name of box.

The first example shows how to access the first element in the array-like object and set its color property to green.

The second example uses a for...of loop to iterate over the array-like object and set the color property for each DOM element.

Make sure to place the JS script tag at the bottom of the body tag in your html file. If you run the index.js file before creating the DOM elements, you will get the error, because the index.js file won't have access to the DOM elements.

Note that the getElementsByClassName method does not return an array, it returns an array-like object, so there are some limitations around it, e.g. you can't use some of the array methods - like forEach.

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