this following piece of code works, but it sort of makes the browser quirk just a bit. Nothing major. I'm wondering if there would be a way to make this more efficient? Can I use caching or somehow populate one select and then just copy it to the other 5. (there are 6 drop downs with a class of 'mask' on the page.)
Any help would be greatly appreciated!
$('.mask').each(function () {
$(this).append($('<option/>').val("").text(""));
for (var i = 1; i < 256; i++) {
$(this).append($('<option/>').val(i).text(i));
}
});
});
this following piece of code works, but it sort of makes the browser quirk just a bit. Nothing major. I'm wondering if there would be a way to make this more efficient? Can I use caching or somehow populate one select and then just copy it to the other 5. (there are 6 drop downs with a class of 'mask' on the page.)
Any help would be greatly appreciated!
$('.mask').each(function () {
$(this).append($('<option/>').val("").text(""));
for (var i = 1; i < 256; i++) {
$(this).append($('<option/>').val(i).text(i));
}
});
});
Share
Improve this question
asked Dec 22, 2010 at 21:27
user342706user342706
2 Answers
Reset to default 11You can create the nodes once then clone them, like this:
var temp = $('<select/>');
$('<option/>').val("").text("").appendTo(temp);
for (var i = 1; i < 256; i++) {
$('<option/>').val(i).text(i).appendTo(temp);
}
temp.children().clone().appendTo('.mask');
Instead of doing a lot of individual appends to the DOM (which is very costly) this batches all the elements up in a document fragment then clones them, appending in batches (one batch per select).
It's much faster (around 3-10 times, as tested here) to build up the HTML yourself in a single string:
var html = "<option value=''></option>";
for (var i = 1; i < 256; i++) {
html += "<option value='" + i + "'>" + i + "</option>";
}
$(".mask").append(html);
See performance test paring the current options in this thread: http://jsperf./appending-options-jquery