Zox
Zox

Reputation: 303

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

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);
    }
}

Upvotes: 1

Views: 2658

Answers (3)

dfsq
dfsq

Reputation: 193271

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/

Upvotes: 1

codeVerine
codeVerine

Reputation: 762

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);
    }
}

Upvotes: 0

isherwood
isherwood

Reputation: 61083

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

Upvotes: 0

Related Questions