我有很多来自同一网站的链接,但是链接不同
<a href="somelink.com/1" title="this link">
</a>
<a href="somelink.com/2" title="this link">
</a>
<a href="somelink.com/3" title="this link">
</a>
<a href="somelink.com/3" title="this link">
</a>
他试图使用该代码,但由于他搜索的是特定网址而非全部网址,因此对我不起作用
var a = document.querySelector('a[href="somelink.com"]');
if (a) {
a.setAttribute('href', 'replacedlink.com')
}
<a href="somelink.com" title="this link">
</a>
我该如何大规模地将其存储到estecifico中的网站的所有URL,例如:somelink.com
答案 0 :(得分:1)
您可以使用attribute selector ^=
来检查href是否以somelink.com
开头。然后,您可以替换网址:
document.querySelectorAll('a[href^="somelink.com"]').forEach(
x => x.href = x.href.replace("somelink.com", "replacedlink.com")
);
<a href="somelink.com/1" title="this link">a
</a>
<a href="somelink.com/2" title="this link">b
</a>
<a href="somelink.com/3" title="this link">c
</a>
<a href="somelink.com/3" title="this link">d
</a>
<a href="otherlink.com/3" title="this link">e
</a>
如果要替换整个链接,可以将href属性设置为新链接:
document.querySelectorAll('a[href^="somelink.com"]').forEach(
x => x.href = "replacedlink.com"
)
<a href="somelink.com/1" title="this link">a
</a>
<a href="somelink.com/2" title="this link">b
</a>
<a href="somelink.com/3" title="this link">c
</a>
<a href="somelink.com/3" title="this link">d
</a>
<a href="otherlink.com/3" title="this link">e
</a>
答案 1 :(得分:0)
Try adding class to the links and then use get element by class and replace the link
<a href="www.google.com" class="abc">my url</a>
var i=document.getElementByClass("abc");
for(let j=0;j<i.length;j++){
i[j].href='newUrl';
}
答案 2 :(得分:0)
对于多个项目,我们可以这样替换:
var a = document.querySelectorAll('.your_attr_class').forEach( (item)=>{
if(item.href.startsWith('http://somelink.com')){
item.href.replace('http://somelink.com','http://replacewith.com');
}
});