Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcode1con1cat
1,836 PointsMy button id = 'toggleList', but have my const = togListB. It seems I can interchange toggleList and togListB, why?
Is it Javascript magic? Is it the IDE's magic (I'm using the workspace provided by you)? Are ids automatically set to a global variable somewhere? Can you explain why the code still works? I want to understand this better.
The Code:
const togListB = document.getElementById('toggleList');
const listDiv = document.querySelector('.list');
toggleList.addEventListener('click', () => { // Note here I use toggleList
if (listDiv.style.display == 'none') {
togListB.textContent = 'Hide List'; // But here I use togListB
listDiv.style.display = 'block';
} else {
togListB.textContent = 'Show List'; // And here I use togListB as well
listDiv.style.display = 'none';
}
});
Thank you!
1 Answer
Steven Parker
231,271 PointsThis is a browser feature. Named elements become properties of the Window object and can be referenced like global variables. But the same specification that defines this also cautions against using it:
As a general rule, relying on this will lead to brittle code. Which IDs end up mapping to this API can vary over time, as new features are added to the Web platform, for example. Instead of this, use document.getElementById() or document.querySelector().