0

I have container with class .headerRightZone this container has elements with class .btn some of them has class .hidden

Goal: I need to choose (write selector) the last visible (button without .hidden class) button

myhtml.html

<div class="headerRightZone">
  <a href="javascript: void(0)" class="btn">Button 1</a>
  <a href="javascript: void(0)" class="btn">Button 2</a>
  <a href="javascript: void(0)" class="btn">Button 3</a>
  <a href="javascript: void(0)" class="btn hidden">Button 4</a>
  <a href="javascript: void(0)" class="btn hidden">Button 5</a>
</div>

mycss.css

.hidden{
  display: none;
}

.btn{
  background-color: #fff;
}

.headerRightZone .btn:not(.hidden):last-of-type{
  background-color: #f00;
}

I wrote:

.headerRightZone .btn:not(.hidden):last-of-type

But it returns an empty array.

Attached jsFiddle Example

What's wrong in the code? Why the array is empty?

tremendows
  • 4,262
  • 3
  • 34
  • 51
Mike Mameko
  • 199
  • 1
  • 2
  • 11
  • 1
    "it returns an empty array" - sounds like this isn't CSS but is instead JavaScript. Could you provide the code you're using here? – James Donnelly Nov 23 '16 at 11:05
  • Attached jsFiddle example. I expected the third anchor should be with red background – Mike Mameko Nov 23 '16 at 11:17
  • if you sure you want third anchor button to be red, you can select nth-child(3) i just update your jsfiddle https://jsfiddle.net/icenova/po3fcuo6/1/ – Horken Nov 23 '16 at 11:33
  • no-no, the count of hidden buttons can change, but the last visible should be red – Mike Mameko Nov 23 '16 at 11:36

1 Answers1

3

The problem here is that last-of-type doesn't work how you are expecting it to.

It will only evaluate based on the element type, in this case a, it doesn't care about classes. The selector you have written can only ever affect the last anchor tag, regardless of what classes it has. So as your last element is not displayed, you are not seeing your styles being set.

Hiding different elements demonstrates this: updated fiddle

To solve your problem, you will need to use javascript or jQuery as this is beyond the capabilities of CSS.

Some good suggestions have already been made before: here

Community
  • 1
  • 1
hairmot
  • 2,975
  • 1
  • 13
  • 26