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.

1

There are 1 best solutions below

0
On

jQuery object containing both a self-closed option element and an array ( $("<option/>", {value: key, text: value }) )

Nah, that is a special form of the jQuery constructor for "creating elements":

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML [and if it does], jQuery attempts to create new DOM elements as described by the HTML.

[…]

The second argument to jQuery() can accept a plain object consisting of a superset of the properties that can be passed to the .attr() method.

Important: If the second argument is passed, the HTML string in the first argument must represent a a simple element with no attributes. As of jQuery 1.4, any event type can be passed in, and the following jQuery methods can be called: val, css, html, text, data, width, height, or offset.

[…]

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 to append, which (as usual) appends all elements from the collection to its elements - in here, the new option to your #year <select> element.