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 trial
Wes Laycock
2,328 PointsWhy doesn't my code work when I switch from a .getElementsByClassName('') to a .querySelectorAll('.')?
My prior code: const kindList = document.getElementsByClassName('error not inappropriate');
what the lesson/instructor ask me to do: const kindList = document.querySelectorAll('.error not inappropriate');
My program will work with the prior code but once I transform it into the next code sentence, It stops working (certain elements don't turn blue).
- I did not touch the for loop below the code which looks like so: for ( let i = 0; i < kindList.length; i += 1 ) { kindList[i].style.color = 'blue' }
- I remembered to use the period (CSS Selector) for using the .querySelectorAll() method
- I go transform the code back and forth between the two methods (.quertSelectAll(), getElementsByClassName()) but only one works, the getElementsByClassName() method.
1 Answer
Corina Meyer
9,990 Pointsyour elements seem to have 3 classes (a single class can not contain a whitespace, this indicates the beginning of a new classname in the attribute). with the querySelectorAll you will have to select them like so
const kindList = document.querySelectorAll('.error.not.inappropriate')
The way you used it, you look for elements with the class "error" and inside those, you search for elements with the tagname "not" and inside of these for elements with the tagname "inappropriate". This works just the way you select elements in css: "." is a class, "#" is an id, without a prefix, it is a tag, and a whitespace means looking for nested elements.
Wes Laycock
2,328 PointsWes Laycock
2,328 PointsI did what you said and it worked perfectly. I love you and envy your knowledge.