Why does this return an error?

All these id’s exist

		let displayNoneArray = ["amtStringLoot", "amtThickStringLoot", "amtCheeseLoot", "amtStingLoot", "amtHoneyLoot", "amtBonesLoot", "amtRawChickLoot", "amtFeatherLoot"]
		let arrayLen = displayNoneArray.length
		for (i = 0; i <= arrayLen; i++) {
			document.getElementById(displayNoneArray[i]).style.display = "none"
		}

but it give this error

VM5281:4 Uncaught TypeError: Cannot read properties of null (reading 'style')
    at <anonymous>:4:48

It seems to be saying that you are trying to read the properties of null.
Try to console.log the element you are trying to retrieve before trying to look at the style property.

amtStringLoot
amtThickStringLoot
amtCheeseLoot
amtStingLoot
amtHoneyLoot
amtBonesLoot
amtRawChickLoot
amtFeatherLoot
undefined
undefined

Do you still need help or you can see the undefined values now so you know the reason for the error?

In addition to what hbar1st is saying, I suggest that you should review hot to properly use a for loop to index through an array. That is another good reason to use the forEach method or at least for...of.

I would also suggest, that if possible, to get the list of nodes dynamically.

ill tell you if I dotnm know

I need help actually.

<span id="amtStringLoot">1</span>
<span id="amtThickStringLoot">2</span>
<span id="amtCheeseLoot">3</span>
<span id="amtStingLoot">4</span>
<span id="amtHoneyLoot" >5</span>
<span id="amtBonesLoot">6</span>
<span id="amtRawChickLoot">7</span>
 <span id="amtFeatherLoot">8</span>

It should just be i < arrayLen not i <= arrayLen in the loop, should it not?

I mean it is still wrong and is going to throw the error asked about in the initial post.

The extra undefined value being logged can be anything for all we know (like a function return value).

Hey, I have got a solution for you; The error in this code is that the loop should use "<" instead of "<=" in the for loop’s condition.
It should be for (i = 0; i < arrayLen; i++) {...}
This is because arrays are zero-indexed in JavaScript, so the last element in the array has an index of arrayLen - 1, not arrayLen.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.