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 trialMagdalena Misiuna
14,873 Pointsjavascript filters with conditional statement
I am trying to make a periodic table using some of Guil's and Reggie's techniques. I have 3 filters set up, but it seems as they work only on certain elements. When I click on metals, it is filtered correctly (all blue elements are selected with red border.) However, when I click on non-metals and metalloids the filtering deselects only some elements but keep red border on others. Anyone can point me where the error lives, or suggest better technique for filters like that?
1 Answer
Steven Parker
231,261 PointsIt looks like you're creating a loop index from one list, but then applying it to other lists. This causes some elements to be skipped.
Instead, use individual loops for each list so the index range will be complete and appropriate, for example:
// filter non metals
nonmetalsBtn.addEventListener('click', ()=> {
for (let i=0; i<nonmetalList.length; i++) {
nonmetalList[i].style.border = '2px solid red';
}
for (let i=0; i<metalList.length; i++) {
metalList[i].removeAttribute('style');
}
for (let i=0; i<metalloidsList.length; i++) {
metalloidsList[i].removeAttribute('style');
}
});
Note that this example also simplifies things by setting just one listener for the button, and performing the loops inside the handler function.
You can condense the code even more if you use designated handlers to take advantage of "event bubbling" and handle groups of buttons with a single function. Similarly, you can use arrays and loops to establish the initial data with more compact code. These concepts might be covered in lessons you have not taken yet.