【问题标题】:How to find the last two elements with the same class in a div and assign them a class?如何在 div 中找到具有相同类的最后两个元素并为它们分配一个类?
【发布时间】:2013-11-04 10:15:38
【问题描述】:
<div id="main-container">
    <div class="box">apple</div>
    <div class="box">bus</div>
    <div class="box">cattle</div>
    <div class="box">dog</div>
    <div class="box">eggplant</div>
    <div class="box">fox</div>
    <div class="box">goat</div>
</div>

如何在“#main-container”中找到最后两个“.box”,然后将它们分配给特定的类?

【问题讨论】:

  • 您可能需要提供一些上下文。可能有更好的方法来做你正在做的事情。
  • 也许回答这个问题会有所帮助:jQuery: Getting the two last list items?
  • @PitaJ 基本上是一个模板正在生成带有“box”类的 div,我无法控制它。但是,我确实知道最后两个不需要显示的 .box。所以我需要两个专门找到它们。

标签: javascript jquery html css


【解决方案1】:

使用slice 方法获取最后两个子元素,然后添加您想要的特定类。

$('#main-container .box').slice(-2).addClass('someclass')

【讨论】:

  • 你应该说你想要一个 jQuery 答案。
  • 我不记得标签说 jQuery,否则我会给出一个 jQuery 答案。无论如何,我想这两个答案将来都会有用。
  • 我不认为他在我回答之前添加了 jQuery 标签。
【解决方案2】:

您可以使用css选择器nth-last-child选择最后2个框:

.box:nth-last-child(-n+2) {}

http://jsfiddle.net/ekDbA/

浏览器支持IE9+ https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child?redirectlocale=en-US&redirectslug=CSS%2F%3Anth-last-child

【讨论】:

    【解决方案3】:

    针对您的具体问题...

    var main = document.getElementById('main-container');
    var boxes = main.getElementsByClassName('box');
    
    boxes[boxes.length - 2].className += ' a-class'; // 2nd to last
    boxes[boxes.length - 1].className += ' a-class'; // last
    

    不过,正如 PitaJ 所说,如果您愿意传达它,可能会有更好的方法来实现您的实际目标。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多