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?
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.You're looking for
a:last-of-type
. Read more about it here: https://css-tricks.com/almanac/selectors/l/last-of-type/The straightforward javascript is:
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).
Why don't you try
$('a:last');
Use
nth-last-child()
. Its pretty useful when you want the last or 2nd to last.https://api.jquery.com/nth-last-child-selector/
http://jsfiddle.net/o5y9959b/