开发者

how to add li between each li using Jquery

开发者 https://www.devze.com 2022-12-20 20:46 出处:网络
i have this HTML CODE <ul id=\'container\'> <li>a</li> <li>b</li> <li>c</li>

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='s开发者_高级运维eparator'></li>
</ul>

what is the best way to do that using jquery?


Like this:

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

$('ul#container').children('li').after(separatorHtml)
$('ul#container').prepend(separatorHtml);


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消