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 trialnathanielcusano
9,808 PointsThe choice of verbose coding in javascript. Why not do it this way... it worked for me.
const toggLelist= document.getElementById('toggleList');
const listDiv = document.querySelector ('.list');
const input= document.querySelector ('input.description');
const p = document.querySelector ('p')[1];
const button = document.querySelector ('button')[1];
1 Answer
Steven Parker
231,269 PointsYou have some errors, this should not have "worked".
Take this line for example:
const p = document.querySelector('p')[1];
Here you are indexing the result of a call to querySelector, but querySelector returns a single element, not an element collection. The result of this assignment would cause p to be undefined.
Even if you substituted querySelectorAll (which returns a collection) and the intended target element was the second paragraph, this code might work as-is but would be fragile and easily broken by the addition of new paragraph elements. The video example of using a combined class and tag in the selector would be much more robust.
nathanielcusano
9,808 Pointsnathanielcusano
9,808 PointsOk thanks but lets say I had like 5 more paragraphs. Wouldn't a need to differentiate them with a different class name every time? Also I thought that querySelector only selects the first <p> element so what does it matter if there are 5 more paragraphs? I don't understand this. Is it possible to just type in the arrays I want like [0, 2, 3] or something. I don't understand the superiority of class, can you help me lol?
Steven Parker
231,269 PointsSteven Parker
231,269 PointsThe advantage of the class is that you can associate it with a particular paragraph, and that will be reliable even if other paragraphs get added in front of it. If you rely on indexing, you would have to update your code when anything is added to the document, even if (and especially if) it was not intended to be affected by the code.
If you wanted paragraphs treated differently, class names make sense; but if you want them all treated the same, then you might use a querySelectorAll and loop through them.
And yes, querySelector only selects the first element, and that's why you cannot use an index with it.