Reputation: 11
I'm trying to filter the displaying of objects in an array based on what a user types into a search box (in this example, by the property 'prev.author'). I'm using a 'for-of' loop. If you check my code, you can see that I put in checks to make sure the individual variable, prev, is defined.
When I run the code, both checks show it is defined. The 'value' variable is set to whatever the user types in the box, & it works. However, when I try to style the individual variable (prev), I get the error message "Uncaught TypeError: Cannot set properties of undefined (reading 'style')". How could this element, prev, be undefined? It seems like I defined it when initializing the loop. Any help would be much appreciated, as I've already spent a few hours on it.
for (const prev of displayedPrevs) {
console.log(prev);
console.log(prev.author);
console.log(typeof prev.author);
// First check to see if prev is defined returns 'defined'
if (typeof prev === 'undefined') {
console.log('undefined');
} else {
console.log('defined')
}
if (prev.author.toLowerCase().trim().includes(value)) {
// Second check to see if prev is defined returns 'defined'
if (typeof prev === 'undefined') {
console.log('undefined');
} else {
console.log('defined');
}
console.log('yes');
prev.style.display = 'block'; // error: "Uncaught TypeError: Cannot read
properties of undefined (reading 'style')"
} else {
console.log('no');
prev.style.display = 'none'; // error: "Uncaught TypeError: Cannot read
properties of undefined (reading 'style')"
}
}
Upvotes: 0
Views: 169
Reputation: 11
I solved it, with the help of some in the comments. For anyone with this same issue, make sure you are trying to change, for example, the style.display property of actual DOM elements that exist in your HTML, not items that only exist in JS.
Upvotes: 1