简体   繁体   English

在JavaScript中从网页中获取URL链接

[英]Getting a URL link from within a webpage in javascript

Basically trying to figure out in JS (Firefox Addon) how to get a URL from within a webpage I'm currently on. 基本上试图在JS(Firefox插件)中弄清楚如何从我当前正在访问的网页中获取URL。 I've looked online but I haven't been able to get it to work. 我已经看过网上了,但无法正常工作。 The specific tag is as follows: 具体标签如下:

<a class="down-btn sec-place" href="http://link.com" view="item for view">Viewing</a>

Its within div, ul and li tags. 它在div,ul和li标签内。 I'm not sure if I need to provide more information, or the actual tags so feel free to tell me. 我不确定是否需要提供更多信息或实际标签,所以请随时告诉我。

Thanks everyone 感谢大家

--edit - 编辑

Thanks everyone so far, in terms of what I've tried I've been usually using some sort of variant of 到目前为止,谢谢大家,就我所尝试的而言,我通常使用的是

document.getElementsByClassName('down-btn sec-place')[0]

and

my_a_dom_node.getAttribute('href', 2);

Typically I get the Reference error: Document not provided error though. 通常,我会收到“ Reference error: Document not provided error

新增区域图片

You can use the document.querySelector to find the element you are looking for 您可以使用document.querySelector查找所需的元素

var link = document.querySelector('.down-btn.sec-place');
var url;

if (link) {
    url = link.href;
}

Just remember that if multiple elements match that selector, it will only return the first matched element. 只要记住,如果多个元素与该选择器匹配,它将仅返回第一个匹配的元素。 If you want to get all of them use document.querySelectorAll instead 如果要全部获取,请改用document.querySelectorAll

The syntax for the selector string is the same as CSS selectors, so if you want to be more specific and select only links under ul and li then switch to ul > li > a.down-btn.sec-place 选择器字符串的语法与CSS选择器相同,因此,如果要更加具体,仅选择ul和li下的链接,请切换到ul > li > a.down-btn.sec-place

尝试

var href = $(".sec-place").attr('href');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM