Extract URL from HTML using Javascript and use it in a function

喜欢而已 提交于 2019-12-11 06:32:36

问题


I need to extract URL link from html.

<a rel="nofollow" href="link" class="1">

There is only one such link on the whole page.

Then I need to add use it as a.href in this function:

function changespan() {
    var spans = document.querySelectorAll('span.image');
    for (var i = spans.length; i--; ) {
        var a = document.createElement('a');
        a.href = "http://domain.com";
        spans[i].appendChild(a).appendChild(a.previousSibling);
    }
}

回答1:


Try this:

function changespan() {
    var spans = document.querySelectorAll('span.image'),
        href = document.querySelector('.nofollow-link').href;
    for (var i = spans.length; i--; ) {
        var a = document.createElement('a');
        a.href = href;
        spans[i].appendChild(a).appendChild(a.previousSibling);
    }
}

but change you link class to something else then 1 it can't start with number:

<a rel="nofollow" href="link" class="nofollow-link">Link</a>

http://jsfiddle.net/Tqv76/2/




回答2:


document.getElementsByTagName("a")[0].getAttribute("href");



回答3:


function changespan() {
    var spans = document.querySelectorAll('span.image');
    for (var i = spans.length; i--; ) {
        var a = document.createElement('a');
        a.href = $(".1").attr('href');
        spans[i].appendChild(a).appendChild(a.previousSibling);
    }
}


来源:https://stackoverflow.com/questions/15341473/extract-url-from-html-using-javascript-and-use-it-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!