I have an array that I want to have displayed in HTML..
I don’t want to write multiple lines for posting each item in the array but all should be exactly the same. ie
var array = [];
//code that fills the array..
$('.element').html('<span>'+array+'</span>');
what I want here is to create a span for each item in the array.
You can do it like this by iterating through the array in a loop, accumulating the new HTML into it’s own array and then joining the HTML all together and inserting it into the DOM at the end:
Some people prefer to use jQuery’s
.each()method instead of theforloop which would work like this:Or because the output of the array iteration is itself an array with one item derived from each item in the original array, jQuery’s
.mapcan be used like this:Which you should use is a personal choice depending upon your preferred coding style, sensitivity to performance and familiarity with
.map(). My guess is that theforloop would be the fastest since it has fewer function calls, but if performance was the main criteria, then you would have to benchmark the options to actually measure.FYI, in all three of these options, the HTML is accumulated into an array, then joined together at the end and the inserted into the DOM all at once. This is because DOM operations are usually the slowest part of an operation like this so it’s best to minimize the number of separate DOM operations. The results are accumulated into an array because adding items to an array and then joining them at the end is usually faster than adding strings as you go.
And, if you can live with IE9 or above (or install an ES5 polyfill for
.map()), you can use the array version of.maplike this:Note: this version also gets rid of the
newHTMLintermediate variable in the interest of compactness.