How do I choose the last 2 items in a list with css nth-child?

后端 未结 4 556
不知归路
不知归路 2021-01-31 08:29

Is it possible? If not, is there a way to do it with jQuery?

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 09:15

    Unfortunately it's impossible.. Disregard this answer and look at spliters answer below.

    If it were to be possible, it would look something like...

    ul li:last-child+li {...}
    

    But this doesn't work, because + will select the immediate sibling after last-child (which is nothing, of course). There is no immediate previous selector.

    There are different ways of achieving this with jQuery, the most performant would be...

    var lastItems = $("#list li");
    lastItems.slice(lastItems.length - 2).addClass("whatever");
    

    http://jsfiddle.net/qkzdJ/

提交回复
热议问题