1

I have some markup like so:

<li>
  <span>
    <div>
      <a href="#" class="anchor menu-active">Afghanistan</a>
      <div class="container menu-visible"></div>
    </div>
   </span>
   <span>
      <div>
        <a href="#" class="anchor">Kabul(AFT)</a>
        <div></div>
      </div>
  </span>
</li>

I wish to select the very last element with the class anchor in terms of the li. The result is that the <a href="#" class="anchor">Kabul(AFT)</a> should be selected. There can be an arbitary amount of elements with this the anchor class within the li.

I came up with this selector: li .anchor:last-of-type, but it selects both elements in there.

How can I select the absolutely last element with the anchor class?

F21
  • 32,163
  • 26
  • 99
  • 170
  • You cannot select the absolutely last element in a DOM having a certain class using CSS. In future you may be able to select the last child having a certain class, but not the very last element regardless of structure. – BoltClock May 09 '12 at 08:23

2 Answers2

0

I don't see your listed items, and seems you put all your items within the same li.

Why don't you make a sub-list:

<li>
  <a href="#">Afghanistan</a>
  <ul>
    <li>
      <a href="#">Kaboul(AFT)</a>
    </li>
   </ul>
</li>

If you are trying to get the last of a selector then you use last-child. If you are trying to get the last element with a specific class then

.anchor:last-of-type {}

is the right choice.

There is this post too.

Community
  • 1
  • 1
Zedrian
  • 909
  • 9
  • 29
  • Unfortunately, I am not able to alter the markup as that is generated by the backend and some other libraries. The `li` in my question is actually within a `ul`, but as I am using YUI, I am running this selection from the markup in the question. – F21 May 09 '12 at 04:21
  • The problem is that your selector that needs to be differentiated with the .anchor class is separated with other selectors and thus the browser will read each item as the last item as shown in this [jsfiddle example](http://jsfiddle.net/8XewF/). You really can't over-ride the template? – Zedrian May 09 '12 at 06:10
  • No, `:last-of-type` selects the last element of its type, not its class. – BoltClock May 09 '12 at 07:21
0

I ended up using some javascript to skirt around the problem as using a clean CSS selector based solution was impossible.

Initially, the plan was to grab the last .anchor and get it's x and y coordinates to calculate a set of coordinates for an overlay.

The solution was to just get the coordinates of the parent li, get it's height, and then do the calculation.

Not as neat as a CSS selector, but it works.

F21
  • 32,163
  • 26
  • 99
  • 170