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 trialTravis Williams
2,886 PointsIs this alternative to getAttribute OK?
I couldn't remember the getAttribute()
method so I found and used the dataset.breed
properties for my comparisons. I get that that breed won't be a dataset property in other applications, but are there other reasons why I shouldn't have used this?
I also used getElementById()
instead of querySelector()
is that an issue?
Here's what I wrote that worked for me
const animalSelect = document.getElementById('animals');
const breedSelect = document.getElementById('breeds');
const breedOptions = document.querySelectorAll('option[data-breed]');
animalSelect.addEventListener('change', () => {
for (let i = 0; i < breedOptions.length; i++) {
if (animalSelect.value !== breedOptions[i].dataset.breed) {
breedOptions[i].hidden = true;
} else if (animalSelect.value === breedOptions[i].dataset.breed) {
breedOptions[i].hidden = false;
}
}
if (breedSelect.value !== "") {
breedSelect.value = "reselect";
}
});
1 Answer
Steven Parker
232,380 PointsSince you already have a reference to the element, using the membership notation is probably even more efficient than getAttribute (not that efficiency is normally a concern). It's certainly a valid choice for getting the data.
Similarly, getElementById is probably more efficient than querySelector. The main advantage of querySelector is versatility — as it can be used with any selector string, not just with ID's.
Travis Williams
2,886 PointsTravis Williams
2,886 PointsAwesome, thanks! This practice really stretched me and I was very excited to see my solution worked even though it was different than the published solution.
Thanks as always for the quick and helpful replies Steven.
Steven Parker
232,380 PointsSteven Parker
232,380 PointsIn programming, there is rarely only one solution to a given task. Thinking of effective alternative strategies is evidence of your learning progress and grasp of the material. Good job!