简体   繁体   English

当不是每个元素都具有选择类jquery时,选择nth-last-child

[英]Select nth-last-child when not every element has the selecting class-jquery

I'm looking for something like the following CSS4 selector in jQuery : :nth-last-match(selector) 我正在寻找类似jQuery的以下CSS4选择器的东西:nth-last-match(selector)

I need to select the second to last element from a list of elements where not every element has a class - Please see the following example highlighting what i am hopeing to achieve. 我需要从不是每个元素都有一个class的元素列表中选择倒数第二个元素-请参阅以下示例,突出显示我希望实现的目标。

 $('.select:nth-last-child(2)').addClass('selected'); 
 .test.selected { color:red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div class="test">a</div> <div class="test select">a</div> <div class="test">a</div> <div class="test select">a</div> <div class="test">a</div> <div class="test">a</div> <div class="test select">EXPECTED SELECTION</div> //This element should be selected <div class="test">a</div> <div class="test select">a</div> <div class="test">a</div> </div> 

Many Thanks. 非常感谢。

You can use .get() method with negative argument value: 您可以使用带负参数值的.get()方法:

var expected = $('div .select').get(-2);
$(expected).css('background', 'red');

So, .get(-1) is the last element of this collection, and .get(-2) is second from the end. 因此, .get(-1)是此集合的最后一个元素, .get(-2)是末尾的第二个元素。
Check the below snippet 检查以下代码段

 var expected = $('div .select').get(-2); $(expected).css('background', 'red'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> <div class="test">a</div> <div class="test select">a</div> <div class="test">a</div> <div class="test select">a</div> <div class="test">a</div> <div class="test">a</div> <div class="test select">EXPECTED SELECTION</div> <div class="test">a</div> <div class="test select">a</div> <div class="test">a</div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM