[英]Get nth-last-child() for a <tr> with a particular class
I wanted to select the 3rd last <tr>
which has the class record
and then add another class to it.我想 select 最后第三个<tr>
有 class record
,然后添加另一个 class 到它。 So for example, I have a table like below:例如,我有一个如下表:
$('tr.record:nth-last-child(3)').addClass('load-next-set'); $('.record:nth-last-child(3)').addClass('load-next-set');
.load-next-set { background-color: tomato; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> <th>Col 4</th> </tr> </thead> <tbody id="tbody"> <tr class="record"> <td>info 1</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr> <td>info 2</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr> <td>info 3</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr class="record"> <td>info 4</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr class="record"> <td>info 5</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr class="record"> <td>info 6</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr> <td>info 7</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr class="record"> <td>info 8</td> <td>info</td> <td>info</td> <td>info</td> </tr> </tbody> </table>
The options that I have tried don't seem to be working.我尝试过的选项似乎不起作用。 Is there another way to do it?还有另一种方法吗?
You can achieve this by using a combination of class selector and the eq function.您可以通过使用 class 选择器和 eq function 的组合来实现此目的。
$('tr.record').eq(-3).addClass('load-next-set')
.load-next-set { background-color: tomato; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> <th>Col 4</th> </tr> </thead> <tbody id="tbody"> <tr class="record"> <td>info 1</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr> <td>info 2</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr> <td>info 3</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr class="record"> <td>info 4</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr class="record"> <td>info 5</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr class="record"> <td>info 6</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr> <td>info 7</td> <td>info</td> <td>info</td> <td>info</td> </tr> <tr class="record"> <td>info 8</td> <td>info</td> <td>info</td> <td>info</td> </tr> </tbody> </table>
Assuming that you only assign the class record
to tr
elements of one table (like in your example):假设您仅将 class record
分配给一个表的tr
元素(如您的示例中所示):
In vanilla javascript:在原版 javascript 中:
var n=3; // example
var trs = document.getElementsByClassName('record');
if(trs.length>=n){
var tr = trs[trs.length-n];
tr.classList.add("another_class");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.