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 trialvarlevi
8,113 PointsChanging the Text Color of all items with the same tag in Javascript
Hi! I need to change the color of all h3 elements on a page when the user clicks a button in vanilla javascript. I've tried loop through an array with all the h3 in it using for loops, but I'm getting an
Uncaught TypeError: Cannot read property 'style' of undefined
at HTMLDivElement.<anonymous>
error. Here's my code:
let darkButton = document.getElementById('dark-button');
darkModeState = false;
darkButton.addEventListener('click', () => {
darkModeState = !darkModeState;
let h3 = document.getElementsByTagName('H3');
if (darkModeState == true) {
document.body.style.backgroundColor = "#111";
document.getElementsByTagName('h1')[0].style.color = '#DDD';
document.getElementsByTagName('h2')[0].style.color = '#DDD';
for (i of h3) {
h3[i].style.color = '#DDD';
}
} else {
document.body.style.backgroundColor = "#FFF";
document.getElementsByTagName('h1')[0].style.color = '#DDD';
document.getElementsByTagName('h2')[0].style.color = '#DDD';
for (i of h3) {
h3[i].style.color = '#DDD';
}
}
})
Thanks in advance for any help!
2 Answers
Ryan Groom
18,674 Pointsvarlevi So when you're using the for of loop, the "i" in the "i of h3" is already referencing the specific iteration of the h3 elements that you're looping through, so rather than using h3[i].style.color you would just use i.style.color! I hope this helps! if not, let me know!
Steven Parker
231,154 PointsTo iterate on the indexes, use "in". Using "of" iterates on the elements themselves as Ryan mentioned.
for (i in h3) {