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

How can I hide elements after exceeding a certain count JavaScript or jQuery? - Stack Overflow

programmeradmin4浏览0评论

I currently have a div with 8 children divs, but only want to display the first four. What's the easiest way to go about this with javascript or jQuery so that even if the children div's change, the last four divs will always be hidden or display: none?

<div class="wrapper">
  <div class="tour">Tour 1</div>
  <div class="tour">Tour 2</div>
  <div class="tour">Tour 3</div>
  <div class="tour">Tour 4</div>
  <div class="tour">Tour 5</div>
  <div class="tour">Tour 6</div>
  <div class="tour">Tour 7</div>
  <div class="tour">Tour 8</div>
</div>

I currently have a div with 8 children divs, but only want to display the first four. What's the easiest way to go about this with javascript or jQuery so that even if the children div's change, the last four divs will always be hidden or display: none?

<div class="wrapper">
  <div class="tour">Tour 1</div>
  <div class="tour">Tour 2</div>
  <div class="tour">Tour 3</div>
  <div class="tour">Tour 4</div>
  <div class="tour">Tour 5</div>
  <div class="tour">Tour 6</div>
  <div class="tour">Tour 7</div>
  <div class="tour">Tour 8</div>
</div>
Share Improve this question asked Mar 7, 2014 at 18:40 cc-testcc-test 431 gold badge3 silver badges11 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

Using css, nth-child

.wrapper > :nth-child(n + 5) {
    display: none;
}

Demo: Fiddle


of jQuery use .slice() since it is faster than the alternate :lt

$('.wrapper > .tour').slice(4).hide()

Demo: Fiddle

Arun P Johny's answer is great, but in case you needed to do this using jQuery:

$('.wrapper .tour:gt(3)').hide();
发布评论

评论列表(0)

  1. 暂无评论