views:

89

answers:

2

Hello i have this HTML CODE

<ul id='container'>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
<li>e</li>
<li>f</li>
</ul>

i want to add

<li class='separator'></li>

between each li's, at the beginning and at last. so my example will look like this:

<ul id='container'>
<li class='separator'></li>
<li>a</li>
<li class='separator'></li>
<li>b</li>
<li class='separator'></li>
<li>c</li>
<li class='separator'></li>
<li>d</li>
<li class='separator'></li>
<li>e</li>
<li class='separator'></li>
<li>f</li>
<li class='separator'></li>
</ul>

what is the best way to do that using jquery?

A: 

Edited to satisfy the commentators ;)

$('li').each(function(){
$(this).after('<li></li>');
}).filter(':first').before('<li></li>');

I still think using each is useful as it makes further changes easier, but You can do it like that:

$('li').after('<li></li>').filter(':first').before('<li></li>');

PS. Pure CSS solution still would be better here. You can do separators with good border or background definitions (with some background position tweaking and paddings)

naugtur
Almost correct, except he specifically wants a "separator" inserted after the last `li` as well.
meagar
And before the first one.
SLaks
Also, you don't need to call `after` in `each`. http://api.jquery.com/after/ : ` Insert content, specified by the parameter, after _each_ element in the set of matched elements.`
SLaks
Thanx guys. I didn't look too much, so I expected the separators only between stuff ;)
naugtur
+2  A: 

Like this:

var separatorHtml = '<li class="separator"></li>'

$('ul#container').children('li').after(separatorHtml)
$('ul#container').prepend(separatorHtml);
SLaks
+1 - OP wanted 'separator' at the beginning and end as well.
patrick dw
http://jsbin.com/uniyu3/edit
SLaks