I have a series of unordered lists wrapped in another unordered list. The task is to separate the individual li tags with commas and omitting the each list's last li tag.
I can do it on an individual list level i.e. When testing with just one list I was able to remove the last comma from the last element. But when I'm trying to apply the JavaScript in affects the last li element of the wrapping ul...
Here is my code:
<script type="text/javascript">
$(document).ready(function () {
$('.tagsList li span').each(function () {
$(this).append(',');
});
var lTag = $('.tagsList li:last span').text().replace(',','');
$('.tagsList li:last span').text(lTag);
});
</script>
<ul class="postsList">
<li>
<ul class="tagsList">
<li><span>tag1</span></li>
<li><span>tag2</span></li>
</ul>
</li>
<li>
<ul class="tagsList">
<li><span>tag1</span></li>
<li><span>tag2</span></li>
</ul>
</li>
</ul>
You should use a slightly modified selector
$('.tagsList li:not(:last-child) span').each(function () {
$(this).append(',');
});
This directly target all the span
elements inside a li
except the last li
of each list.