简体   繁体   中英

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

新增区域图片

You can use the document.querySelector to find the element you are looking for

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

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

尝试

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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