views:

150

answers:

4

Is there a CSS selector for the last occurrence of a class on a page?

Say i have this HTML

<dd>
    <span>
        <a class="required" id="forename">foo</a>
    </span>
</dd>
<dd>
    <span>
        <a class="required" id="surname">bar</a>
    </span>
</dd>

Is there a CSS selector that would return the a tag with the ID of surname. Something like .required:last maybe?

Will be using Prototype if that matters?

+2  A: 

CSS3 has the :last-child selector, but not many browsers support it.

If you can use jquery, you can do:

$("a.required:last")
David
A: 

:last-child is a CSS2 selector. It isn't supported in IE6-7, Safari 3.

If you know the ID of the A, why not just use that? a#surname.

Another workaround is to just add "last" as another class to the last DD.

kmiyashiro
:first-child is CSS2/CSS2.1 http://www.w3.org/TR/CSS2/however :last-child is CSS3http://www.w3.org/TR/2009/PR-css3-selectors-20091215/#last-child-pseudo
David
The html sample was just to clarify my point, the actual source code is dynamic and would look nothing like that. I always thought that when you used something like jQuery or in my case Prototype that CSS selectors were not restricted by browsers but instead use the supplied selector engine, Sizzle in jQuery's case.
seengee
+1  A: 

Using Prototype:

var sel = $(document.body).select('a.required').toArray()
var last = sel[sel.length-1]

(alternately: var last = sel.last())

There may be an easier way.

Diodeus
according to this page (http://www.prototypejs.org/api/utility/dollar-dollar) last-child should work with Prototype, is there a reason you havent used that method?
seengee
i see last-child isnt actually what i want anyway...
seengee
actually, `$(document.body).select('a.required').last()` works just fine!
seengee
Cool, I'm a little rusty on my Prototype.
Diodeus
A: 

:last-of-type can work in some circumstances (when all .required elements have a common parent), but support is spotty. (Edit: no it won't, last-of-type only takes element name in account.) Use Javascript if that works for you, or add a last class in HTML.

@snaken: :last-child (CSS2 actually) is something very different: it selects elements which are last children of their parents. I.e.

<div>
  <a class="required">...</a>
  <a class="required">...</a>
  <a>...</a><!-- this is :last-child! -->
</div>

required:last-child will actually be empty here, because none of the .required elements are last children.

Tgr