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.
for (var i = 0; i < array.length; i++) {
$(".element").append('<span>' + array[i] + '</span>');
}
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(""));
here is solution, i create a text field to dynamic add new items in array my html code is
<input type="text" id="name">_x000D_
<input type="button" id="btn" value="Button">_x000D_
<div id="names">_x000D_
</div>
_x000D_
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()_x000D_
{ _x000D_
function display_array()_x000D_
{_x000D_
$("#names").text('');_x000D_
$.each(names,function(index,value)_x000D_
{_x000D_
$('#names').append(value + '<br/>');_x000D_
});_x000D_
}_x000D_
_x000D_
var names = ['Alex','Billi','Dale'];_x000D_
display_array();_x000D_
$('#btn').click(function()_x000D_
{_x000D_
var name = $('#name').val();_x000D_
names.push(name);// appending value to arry _x000D_
display_array();_x000D_
_x000D_
});_x000D_
_x000D_
});_x000D_
_x000D_
showing array elements into div , you can use span but for this solution use same id .!
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>');
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>`;
});
Source: Stackoverflow.com