开发者

CSS selector for the last occurrence of a class on a page

开发者 https://www.devze.com 2022-12-30 06:25 出处:网络
Is there a CSS selector for the last occurrence of a class on a page? Say i have this HTML <dd> <span>

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?


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.


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

If you can use jquery, you can do:

$("a.required:last")


: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.

0

精彩评论

暂无评论...
验证码 换一张
取 消