js999
js999

Reputation: 2083

how to create a list of span for a given array

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 like that:

"<span>user1</span><span>user2</span>"

I did try the following code

$('<span/>').text(users); 

but it does not work properly, any ideas?

Upvotes: 3

Views: 402

Answers (3)

KooiInc
KooiInc

Reputation: 122916

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;
    }
);

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337580

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

Upvotes: 2

sQVe
sQVe

Reputation: 2015

This would work:

var users = ['user1', 'user2'];

$.each(users, function() {
    $("<span>", { text : this }).appendTo("body");
});

Upvotes: 8

Related Questions