如何获取网站的最后一个锚点元素 [英] How to get the last anchor element of a website

查看:109
本文介绍了如何获取网站的最后一个锚点元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无论DOM树的结构如何,我都需要获取网站的最后一个锚点.

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

我尝试过:

$(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")

这带来了明显的改善:

$(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?

奖励回合

到目前为止,沿着CSS/JavaScript/JQuery的行列,对这个问题的回答非常好.但是,您能否补充一下您的答案是否与跨浏览器兼容?

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?

推荐答案

简单的javascript是:

The straightforward javascript is:

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

这与所有仅了解DOM级别1(即,大约2000年-Internet Explorer 5和Netscape 6)的浏览器都可以跨所有浏览器进行跨浏览器兼容.

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

这篇关于如何获取网站的最后一个锚点元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆