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

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

Solve - Cannot set property 'display' of Undefined #

The "Cannot read property 'display' of undefined" error occurs when trying to set the display property on an undefined value. To solve the error, make sure you access the display property after accessing the style property on a valid DOM element.

cannot set property display of undefined

Here's an example of how the error occurs.

index.js
const elements = []; // โ›”๏ธ Cannot set properties of undefined (setting 'display') elements[0].display = 'block';

Here's the HTML code for a working example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="container">Content 1</div> <div class="container">Content 2</div> <div class="container">Content 3</div> <!-- โœ… GOOD - div already exists โœ… --> <script src="index.js"></script> </body> </html>
Notice that we placed the script below the code that creates the div elements. Had we placed the script above the DOM elements, we wouldn't be able to access them from inside the index.js file.

Here's the related JavaScript code.

index.js
const elements = document.getElementsByClassName('container'); console.log(elements); // ๐Ÿ‘‰๏ธ [div.container, div.container, div.container] // โœ… Update display property of first element elements[0].style.display = 'block'; // โœ… Update display property for all elements in the NodeList for (const element of elements) { element.style.display = 'block'; }

We used the getElementsByClassName method to get an array-like object that contains the DOM elements with a class of container.

The first example shows how to update the display property on the first element in the Node list - we access the element at position 0 and update the property directly.

If you need to set the display property for all of the elements with a specific class, you can use the for...of loop to iterate over the array-like objects.

On each iteration, we set the display property of the element to block.

Note that the elements variable does not store a native JavaScript array, so there are some limitations around it, e.g. you can't use the forEach method to iterate over it.

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