2013-03-11 54 views
1

我需要從html中提取URL link使用Javascript從HTML中提取URL並在函數中使用它

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

整個頁面只有一個這樣的鏈接。

然後我需要將其添加作爲a.href在這個函數:

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

你可以發佈你的HTML,其中的「鏈接」需要從提取? – DanC 2013-03-11 14:47:23

+0

如果你知道如何使用'querySelectorAll',那有什麼問題? oO – VisioN 2013-03-11 14:48:36

+0

我只是沒有格式化問題。標記鏈接使用類標記聰明的事情做? – Zox 2013-03-11 14:48:47

回答

1

試試這個:

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

但改變你的鏈接類別的東西,然後1它不能以數字開頭:

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

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

+0

工作得很好。感謝您提示類不能以數字開頭。 – Zox 2013-03-11 15:18:54

+0

不客氣。如果你接受了答案(和之前的答案),我將不勝感激。 – dfsq 2013-03-11 15:27:20

+0

我不知道有這個選項。我將如何結合函數changespan1和另一個讓我們說changepan2? – Zox 2013-03-11 15:40:48

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

所以我說a.href = document.getElementsByTagName(「a」)[0] .getAttribute(「href」); ? – Zox 2013-03-11 14:51:20

+0

我會這樣想的。搏一搏。 – isherwood 2013-03-11 14:54:31

+0

[0]意味着頁面中的第一個錨,所以我不確定這是否適合您的情況。 – isherwood 2013-03-11 14:55:28

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

1)沒有jQuery。 2)不要做那樣的事情(在循環中查詢DOM)。 – dfsq 2013-03-11 14:55:21

+0

我們都知道有jQuery。那你爲什麼假裝不存在? – codeVerine 2013-03-11 15:03:19

+0

你怎麼知道OP有jQuery? – dfsq 2013-03-11 15:04:05