如何通过变量访问HTMLCollection中的指定元素?
Hey, I get exactly where you're stuck here. Let's walk through this step by step.
You've got an HTMLCollection stored in tabcontent with two members: Drums and Animals. You set activeTabName = "Drums", and while tabcontent.Drums pulls up the right element, tabcontent.activeTabName spits out undefined. That's super frustrating, but the fix is straightforward once you understand why it's happening.
Why tabcontent.activeTabName fails
When you use dot notation (.), JavaScript looks for a property literally named activeTabName on the tabcontent collection. Since your HTMLCollection only has Drums and Animals as properties, it can't find one called activeTabName—hence the undefined. It doesn't care about the value stored inside your activeTabName variable here.
The solution: Bracket notation
To use the value of your variable as the property key, switch to bracket notation ([]). Here's how to update your code:
var activeTabName = "Drums"; console.log(tabcontent[activeTabName]); // This will correctly log the Drums element from your HTMLCollection
Why this works
Bracket notation evaluates whatever is inside the brackets first. So when you write tabcontent[activeTabName], JavaScript grabs the value of activeTabName (which is "Drums"), then looks for that property name on tabcontent—exactly what you want.
A quick analogy to drive it home
Think of it like looking up a word in a dictionary. If you have a note that says "look up 'Drums'", dot notation would be trying to find the word "note" in the dictionary, while bracket notation uses the content of the note to find "Drums". Here's a simple object example to make it concrete:
const instrumentDict = { Drums: "bass drum", Animals: "elephant" }; const lookupKey = "Drums"; console.log(instrumentDict.lookupKey); // undefined (looks for a key named "lookupKey") console.log(instrumentDict[lookupKey]); // "bass drum" (uses the value of lookupKey)
This same logic applies to HTMLCollection because it's an array-like object with named properties.
内容的提问来源于stack exchange,提问作者Dezmond H

