I have a question about how jQuery's .append function works in the following segment of code that dynamically adds values to a select box:
for (var i=currentYear; i >= minYear; i--){
$('#year').append($("<option/>", { value: i, text: i}));
}
I already know that this code does work, as I've used .append in this way before after finding similar code online during a google search. However, the webpage I found the similar code on (https://stackoverflow.com/a/3155663/3120918) did not explain why it works. I ready the official jQuery documentation page on the .append function (http://api.jquery.com/append/), but it did not say anything about passing in a single jQuery object containing both a self-closed option element and an array ( $("<option/>", {value: key, text: value })
) as the single parameter to the append function. I was hoping that someone could explain to me how and why this works.
Nah, that is a special form of the jQuery constructor for "creating elements":
So what does happen here is the construction of a new
<option>
element with given value and text, which is wrapped in a jQuery collection. This is then passed toappend
, which (as usual) appends all elements from the collection to its elements - in here, the new option to your#year
<select>
element.