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


Borislav Hadzhiev

Last updated: Oct 19, 2021


Check out my new book

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.

const elements = []; // ⛔️ Cannot set properties of undefined (setting 'display') elements[0].display = 'block';

Here's the HTML code for a working example.

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

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) { = '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.
Use the search field on my Home Page to filter through my more than 3,000 articles.