Let\'s say I have an object which looks like that:
var users = [\'user1\', \'user2\'];
For this object I would like to create a list of span li
Assuming users
should contain strings only, try this:
var users = ['user1', 'user2'];
for (var i = 0; i < users.length; i++) {
$("<span />").text(users[i]).appendTo("body");
};
Example fiddle
This would work:
var users = ['user1', 'user2'];
$.each(users, function() {
$("<span>", { text : this }).appendTo("body");
});
You also can use the Array.map
method:
['user1', 'user2'].map(
function(a){
$('<span/>').html(a).appendTo($('body')); return a;
}
);
Or even shorter:
$(['user1','user2'].map(function(a){return '<span>'+a+'</span>'}).join(''))
.appendTo('body');
Or even Array.filter
;)
['user1', 'user2'].filter(
function(a){
$('<span/>').html(a).appendTo($('body')); return true;
}
);
Or jQuery.each
on a jQuery object derived from the Array
$(['user1', 'user2']).each(
function(i,a){
$('<span/>').html(a).appendTo($('body')); return true;
}
);