Equivalent of document.createElement('option') in jQuery

Viewed 181

I just want to append or add some option element in to a select element. The elements that I am going to append are the results of an iteration. In each iteration I will create an option and add that in to a select element. I need to perform the following logic, but in jQuery.

keys.forEach(item => {
  var elem = document.createElement('option')
  elem.textContent = item
  document.querySelector("#Select").appendChild(elem)
}
1 Answers

The equivalent of this createElement() in jQuery is to provide the entire element string to the jQuery object constructor: $('<option />'). Note that you can also set properties and call methods from the constructor as well by providing an object to the second argument. The direct translation of the logic would look like this:

keys.forEach(item => {
 $('<option />', { text: item }).appendTo('#Select');
});

However it's worth noting that this approach requires a DOM access, as well as defining a new jQuery object, for every iteration of the loop. A more performant approach is to use map() instead of forEach() to build an array of strings to be appended to the DOM, like this:

let options = keys.map(item => `<option>${item}</option>`); // optional: join('')
$('#Select').append(options);
Related