15

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.

Syscall
  • 19,327
  • 10
  • 37
  • 52
captainrad
  • 3,760
  • 16
  • 41
  • 74

6 Answers6

47

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:

var array = [...];
var newHTML = [];
for (var i = 0; i < array.length; i++) {
    newHTML.push('<span>' + array[i] + '</span>');
}
$(".element").html(newHTML.join(""));

Some people prefer to use jQuery's .each() method instead of the for loop which would work like this:

var array = [...];
var newHTML = [];
$.each(array, function(index, value) {
    newHTML.push('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

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 .map can be used like this:

var array = [...];
var newHTML = $.map(array, function(value) {
    return('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));

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 the for loop 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 .map like this:

var array = [...];
$(".element").html(array.map(function(value) {
    return('<span>' + value + '</span>');
}).join(""));

Note: this version also gets rid of the newHTML intermediate variable in the interest of compactness.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
7

Use any examples that don't insert each element one at a time, one insertion is most efficient

 $('.element').html( '<span>' + array.join('</span><span>')+'</span>');
charlietfl
  • 170,828
  • 13
  • 121
  • 150
6

Original from Sept. 13, 2015:
Quick and easy.

$.each(yourArray, function(index, value){
    $('.element').html( $('.element').html() + '<span>' + value +'</span>')
});

Update Sept 9, 2019: No jQuery is needed to iterate the array.

yourArray.forEach((value) => {
    $(".element").html(`${$(".element").html()}<span>${value}</span>`);
});

/* --- Or without jQuery at all --- */

yourArray.forEach((value) => {
    document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});
T.CK
  • 411
  • 4
  • 6
2
for (var i = 0; i < array.length; i++) {
    $(".element").append('<span>' + array[i] + '</span>');
}
trapper
  • 11,716
  • 7
  • 38
  • 82
  • This code desires to be refactored for many reasons. You could store the `var $element = $('.element')` into a variable before the loop. This would avoid the creation of a new jQuery object in every loop cycle. Also, calling append on every loop cycle is not very performant. The solutions that create a string and update the DOM with a single call are much more performant. – Pierre Spring Dec 12 '16 at 09:36
  • Or not use jQuery at all of course. Only OP will know if that is necessary or just a premature optimisation. – trapper Dec 12 '16 at 10:36
1

You should use $.map for this:

var array = ["one", "two", "three"];

var el = $.map(array, function(val, i) {
  return "<span>" + val + "</span>";
});

$(".element").html(el.join(""));

jsFiddle demo

DᴀʀᴛʜVᴀᴅᴇʀ
  • 7,681
  • 17
  • 73
  • 127
Chris Abrams
  • 39,732
  • 19
  • 51
  • 57
-1

here is solution, i create a text field to dynamic add new items in array my html code is

 <input type="text" id="name">
  <input type="button" id="btn" value="Button">
  <div id="names">
  </div>

now type any thing in text field and click on button this will add item onto array and call function dispaly_arry

$(document).ready(function()
{  
 function display_array()
 {
  $("#names").text('');
  $.each(names,function(index,value)
  {
    $('#names').append(value + '<br/>');
  });
 }
 
 var names = ['Alex','Billi','Dale'];
 display_array();
 $('#btn').click(function()
 {
  var name = $('#name').val();
  names.push(name);// appending value to arry 
  display_array();
  
 });
 
});
 

showing array elements into div , you can use span but for this solution use same id .!

Mohsin Shoukat
  • 1,190
  • 1
  • 13
  • 22