javascript 通过类名获取 HREF 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20821749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 19:22:53  来源:igfitidea点击:

Get HREF value by class name

javascripthtml

提问by Naveen Gamage

I'm trying to get href valueof a specific anchor tag placed on a html page.

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

html tag structure

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>

How do I get the href value from above anchor tag using buttonGoclass name?

如何使用buttonGo类名从上面的锚标记获取 href 值?

回答by

A single line of plain Javascript will give you what you need:

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

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

But, if you aren't sure how many times you need to use parentNode, you have to use a loop:

但是,如果您不确定需要使用多少次parentNode,则必须使用循环:

var anchor = document.getElementsByClassName("buttonGo")[0];
do{
anchor = anchor.parentNode;
} while(anchor.nodeName.toLowerCase() != "a");
var href = anchor.href;

Demo: Solution One(created by Milche Patern) and Solution Two

演示:解决方案一(由Milche Patern创建)和解决方案二

回答by SLaks

Using jQuery:

使用jQuery:

$('.buttonGo').closest('a').attr('href');

Without jQuery, you'll need to start with document.getElementsByClassName('buttonGo'), then crawl up parentElementuntil you find an a.

如果没有 jQuery,您需要从 开始document.getElementsByClassName('buttonGo'),然后向上爬,parentElement直到找到一个a.

jQuery demo

jQuery 演示

回答by BSB

If you want to get attribute of tag on which you are clicking, use:

如果要获取单击的标签的属性,请使用:

$(this).attr("href");