views:

89

answers:

4

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.

+1  A: 

Try this:

$.each(data.posts, function(i, post){ 
 $('<li >', {id: this.id , name: post.tags.join(' ')});  
});
Jacob Relkin
+10  A: 

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

nickf
Thanks! works perfectly
Alex
+1, `class` is a [future reserved word](http://bclary.com/2004/11/07/#a-7.5.3) all of them should be avoided as identifiers...
CMS
The above assumes tags is an array (which, apparently it is in Alex's case). If tags is a string, you would could do either "tags.split(',').join(' ')" or "tags.replace(/,/g, ' ')"
broofa
You can do 'class' as the key as well, with quotes
rpflo
A: 
$.each(data.posts, function(i, post) {
    $('<li >', {id: this.id , name: post.tags.replace(/[,]/g, ' ')})
});
Joel Coehoorn
A: 

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(' '));
Jesse
This will only replace the first ','. To replace all, you need to pass a regex with the 'g' option set as the first arg, as in my comment above. (And, of course, this also assumes tag is a String, not an Array)
broofa
oops, I hadn't actually looked at that part, as mentioned, I copied the code from above. The addClass is the correct way to add classes, as opposed to a "className" attribute, which is what I was demonstrating.I have adjusted the code to properly concat the tags, sorry about that.
Jesse