How to get the last anchor element of a website

2019-08-06 01:18发布

I am in need of obtaining the very last anchor of a website, regardless of the DOM tree structure.

I have tried:

$(document).ready(function(){
    var lastAnchor = $(this).find("a:last-child");
    alert(lastAnchor);
});

However I get all the last anchors that exist inside any element, which contains at least one anchor in it. I understand that this can be converted into an array and from there one may extract the last element... but that's just not the right approach. So what is the right approach?

Fun fact: After messing around with the selectors for some time I came up with:

$(this).find("a:last-child").find(":last-child")

Which lead to the obvious improvement:

$(this).find("a:last-child :last-child")

But I find this solution to be both inefficient and cumbersome. I refuse to believe that a better selector does not exist.

I think I am missing something obvious but it hasn't hit me yet.

Can anyone please enlighten me to whether there is a better way to do this or am I crying wolf for no reason?

EDIT: Bonus Round

Very good answers have been posted to this question thus far, all along the lines of CSS/JavaScript/JQuery. However could you kindly add whether or not your answer is cross browser compatible?

5条回答
We Are One
2楼-- · 2019-08-06 01:38

I believe you want something like $("a").last()

This will look at all anchor elements in the page and give you the very last one that is retrieved.

Using just CSS selectors is tricky, since those tend to be dependant on the DOM arrangement, and you want the selector to be DOM agnostic. For example the a:last-child selector will only return an anchor tag that is the last element in its parent. If the last anchor on a page is not the last element in its parent, using that selector may not be helpful to you.

查看更多
爷、活的狠高调
3楼-- · 2019-08-06 01:42

You're looking for a:last-of-type. Read more about it here: https://css-tricks.com/almanac/selectors/l/last-of-type/

查看更多
我命由我不由天
4楼-- · 2019-08-06 01:45

The straightforward javascript is:

var anchors = document.getElementsByTagName("a");
var lastAnchor = anchors[(anchors.length - 1)];

This is cross-browser compatible across all browsers all the way back to those browsers which understand only DOM Level 1 (ie. circa 2000 - Internet Explorer 5 and Netscape 6).

查看更多
看我几分像从前
5楼-- · 2019-08-06 01:52

Why don't you try $('a:last');

查看更多
Evening l夕情丶
6楼-- · 2019-08-06 01:53

Use nth-last-child(). Its pretty useful when you want the last or 2nd to last.

$(this).find("a:nth-last-child(1)")

https://api.jquery.com/nth-last-child-selector/

http://jsfiddle.net/o5y9959b/

查看更多
登录 后发表回答