最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to find the last two elements with the same class in a div and assign them a class? - Stack Overflow

programmeradmin3浏览0评论
<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>

How do I find the last two ".box" within "#main-container" and then assign them with a specific class?

<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>

How do I find the last two ".box" within "#main-container" and then assign them with a specific class?

Share Improve this question edited Nov 4, 2013 at 2:14 Terry 66.3k16 gold badges105 silver badges126 bronze badges asked Nov 4, 2013 at 1:10 Katie ChenKatie Chen 333 bronze badges 3
  • 3 You may want to provide some context. There may be a better way to do what you're doing. – PitaJ Commented Nov 4, 2013 at 1:12
  • 1 Maybe answer to this question will help: jQuery: Getting the two last list items? – Shad Commented Nov 4, 2013 at 1:14
  • @PitaJ basically a template is generating divs with the class 'box' and I have no control over it. However, I do know the last two .box I need not to show. So what I need to two is find them specifically. – Katie Chen Commented Nov 4, 2013 at 1:42
Add a ment  | 

3 Answers 3

Reset to default 7

Use the slice method to get the last 2 child elements & then add a specific class you wanted.

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

You can select the last 2 boxes with the css selector nth-last-child:

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

http://jsfiddle/ekDbA/

browser support IE9+ https://developer.mozilla/en-US/docs/Web/CSS/:nth-last-child?redirectlocale=en-US&redirectslug=CSS%2F%3Anth-last-child

For your specific question...

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

As PitaJ said, though, there may be a better way to achieve your actual goal, if you would convey it.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论