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 trialHowie Yeo
Courses Plus Student 3,639 PointsIf we are using .each() to iterate through each item, how does $select.append($option) add in ALL the options?
Hi,
To cycle over the menu links, we used .each() method and making changes to them. How does that include ALL the options element when added --- $select.append($option); when it is only looping each at a time ? (I would assume it would append 1x option, not all?)
//Create a select and append to #menu
var $select = $("<select></select>");
$("#menu").append($select);
//Cycle over menu links
$("#menu a").each(function() {
var $anchor = $(this);
//Create an option
var $option = $("<option></option>");
//option's value is the href
$option.val($anchor.attr("href"));
//options's text is the text of link
var anchorText = $anchor.text();
$option.text(anchorText);
//append option to select
$select.append($option);
});
1 Answer
Gabriel D. Celery
13,810 PointsThe $().each() method is essentially a loop.
If you take a look at the code you can see that between the braces of .each() you put a function that generates an "option" tag and puts it between the "select" tags (one option element of the drop down menu).
The $("#menu a") part tells the .each() method, that you want to iterate through each "a" tag that can be found inside the div with the "menu" id.
What happens here is that every time the method finds an "a" tag it executes the function that you put inside the .each() method.
In this case it executes the function six times thus adds 6 "option" tags to the website.
MOD NOTE: Change from "Comment" to "Answer" so that it is able to be up-voted and/or marked as "Best Answer"