我正在尝试获取放置在html页面上的特定 anchor 标记的 href值

html标签结构

<a rel="nofollow" title="some title" href="http://www.this-is-what-i-need.com/just-this.html"><span><em class="buttonGo"></em>Go to this page</span></a>

如何使用 buttonGo 类名称从 anchor 标签上方获取href值?

最佳答案

一行简单的Javascript将为您提供所需的内容:

var href = document.getElementsByClassName("buttonGo")[0].parentNode.parentNode.href;

但是,如果不确定要使用parentNode多少次,则必须使用循环:
var anchor = document.getElementsByClassName("buttonGo")[0];
do{
anchor = anchor.parentNode;
} while(anchor.nodeName.toLowerCase() != "a");
var href = anchor.href;

演示:Solution One(由Milche Patern创建)和Solution Two

关于javascript - 通过类名称获取HREF值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20821749/

10-12 12:40
查看更多