问题
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