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

avatar

Borislav Hadzhiev

Last updated: Jul 24, 2022

banner

Check out my new book

Solve - Cannot set property 'color' of Undefined #

The "Cannot set property 'color' of undefined" error occurs when setting the color property on an undefined value. To solve the error, check if the value is of the expected type before setting the color 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 have to 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 JavaScript 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 method 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 on 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 doesn't return an array, it returns an array-like object. There are some limitations with array-like objects. For example, they don't implement some of the array methods (e.g. forEach).

You can use the Array.from method to convert the array-like object to an array.

index.js
const elements = Array.from(document.getElementsByClassName('box')); console.log(elements); // 👉️ [div.box, div.box, div.box] elements.forEach(element => { element.style.color = 'green'; });

The function we passed to the Array.forEach method gets called with each element in the array.

On each iteration, we set the color property on the current DOM element to green.

Use the search field on my Home Page to filter through my more than 3,000 articles.