cc-test
cc-test

Reputation: 43

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

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>

Upvotes: 1

Views: 1199

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149020

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

$('.wrapper .tour:gt(3)').hide();

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388346

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

Upvotes: 9

Related Questions