Add class to the last <li> in a group of <ul>

被刻印的时光 ゝ 提交于 2021-01-27 10:42:58

问题


I have a group of <ul>'s created dynamically and i need a class added to the last <li> of each one.

I have:

$('ul li:last').each(function(){
    $(this).addClass("last");
});

But this only adds a class="last" to the last <ul> not in all of the <ul>'s.

I want the last <li> of each <ul> to get added the class, not just the last <ul>.


回答1:


:last, a propriety jQuery selector, pops off the last element from the set and returns it.

:last-child, the CSS selector, selects the last child of each ancestor element.

$('ul li:last-child').addClass('last');

jsFiddle.

As a side note, you don't need to use each() there. The addClass() will be ran over each item in the jQuery set.



来源:https://stackoverflow.com/questions/9185361/add-class-to-the-last-li-in-a-group-of-ul

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!