Reputation: 153
I have a looping function creating:
<li id="id1" name="Tag1,Tag2,Tag3">
<li id="id2" name="Tag1,Tag2,Tag3">
$.each(data.posts, function(i, post){
$('<li >', {id: this.id , name: post.tags})
});
How do I replace the commas between the tags with spaces. Also is there a way I can send the tags to a "class" attribute instead of "name". It seems to not work in Safari.
Upvotes: 4
Views: 2227
Reputation: 10466
Use the replace string method (as mentioned in other replies) to replace the commas.
As for the classes, add them like this:
$('<li >', {id: this.id }).addClass(post.tags.join(' '));
Upvotes: -1
Reputation: 546075
What you probably want is this:
$('<li >', {id: this.id , className : post.tags.join(' ')})
By default, when you cast an array to a string, it get concatenated with commas as you have seen. Using join()
will solve the problem.
Also, class
is a reserved keyword in all browsers (though some won't throw an error if you use it), so the attribute you should use for setting the class is called className
Upvotes: 10
Reputation: 415840
$.each(data.posts, function(i, post) {
$('<li >', {id: this.id , name: post.tags.replace(/[,]/g, ' ')})
});
Upvotes: 0
Reputation: 163258
Try this:
$.each(data.posts, function(i, post){
$('<li >', {id: this.id , name: post.tags.join(' ')});
});
Upvotes: 1