2

I have a listing of events and I want the last item to have a different style to the others. Which I've achieved this using the :last-of-type selector and it works fine.

The events can be filtered, so I'm using some jQuery to show/hide events. If the last event is hidden the :last-of-type selector no longer works, as the div is just hidden with the addition of a class.

To try and get around this, I've tried to use the :not() selector as well, but I'm not getting the result I expect.

Here's a quick mockup of the general idea:

$('.box').click(function(){
  $(this).addClass('hidden');
});

$('#showBoxes').click(function(){
  $('.box').removeClass('hidden');
  return false;
});
.box {
  padding: 10px;
  margin-bottom:10px;
  background-color: #f00;
}

.hidden {
  display: none;
}

.box:not(.hidden):last-of-type {
  background-color: #ff0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box">
  My First Event
</div>
<div class="box">
  Conference 117
</div>
<div class="box">
  Christmas Party
</div>
<div class="box">
  Another Event with some more content - Click to hide!
</div>

<p><a id="showBoxes" href="">Show All Boxes</a></p>

So if the last item is hidden, how can the next item take on the css? Is this even possible like this?

Adam Lobo
  • 237
  • 1
  • 8
  • if element is display none then you can not access it. So you can not track .hidden class with css not apply OP base on hidden element. – Parth Trivedi Dec 15 '15 at 15:59
  • 1
    This qeustion was already asked here http://stackoverflow.com/questions/2175694/jquery-nth-child-that-is-currently-visible and here http://stackoverflow.com/questions/32355054/how-to-get-nth-child-selector-to-skip-hidden-divs-using-css-only/32380418#32380418 – Hans. M. Dec 15 '15 at 16:03
  • (Yes, the duplicate is about `nth-of-type`, but `last-of-type` is an application of `nth-of-type`.) – Frédéric Hamidi Dec 15 '15 at 16:04
  • @FrédéricHamidi So if I can't combine two selectors, would a viable solution be to loop over the divs with jQuery and add a 'last' class on to the last visible element? – Adam Lobo Dec 15 '15 at 16:18
  • @Lobo, yes, that solution would be viable. That's what jQuery Mobile does, actually. – Frédéric Hamidi Dec 15 '15 at 16:28

0 Answers0