使用JavaScript更改具有特定ID的所有URL

时间:2019-04-12 10:13:36

标签: javascript html arrays

我有一个html代码来下载这样的文件:

<a class="wp-block-button__link has-background has-vivid-green-cyan-background-color" href="https://github.com/pbatard/rufus/releases/download/v3.5/rufus-3.5.exe" rel="nofollow noopener noreferrer">Download (Installer)</a>
<a class="wp-block-button__link has-background has-vivid-green-cyan-background-color" href="https://github.com/pbatard/rufus/releases/download/v3.5/rufus-3.5p.exe" rel="nofollow noopener noreferrer">Download (Portable)</a>

我希望class="wp-block-button__link标记中的所有URL都这样更改:

<a class="wp-block-button__link has-background has-vivid-green-cyan-background-color" href="mydomain.com/get/?url=https://github.com/pbatard/rufus/releases/download/v3.5/rufus-3.5p.exe" rel="nofollow noopener noreferrer">Download (Portable)</a>
<a class="wp-block-button__link has-background has-vivid-green-cyan-background-color" href="mydomain.com/get/?url=https://github.com/pbatard/rufus/releases/download/v3.5/rufus-3.5.exe" rel="nofollow noopener noreferrer">Download (Installer)</a>

我目前正在使用Javascript更改它,

let a = document.querySelector('.wp-block-button__link');
a.href = "mydomain.com/get/?url=" + a.href
console.log(a.outerHTML)

我现在使用的javascript代码只能更改一个URL,我想更改class="wp-block-button__link"标记中的所有URL。

如何使我使用的javascript代码更改标签class="wp-block-button__link"中的所有URL,而不仅仅是一个URL?

2 个答案:

答案 0 :(得分:2)

使用querySelectorAllforEach

let allLinks = document.querySelectorAll('.wp-block-button__link');
allLinks.forEach(a => {
    a.href = "mydomain.com/get/?url=" + a.href;
    console.log(a.outerHTML);
});

答案 1 :(得分:1)

使用document.querySelectorAll()并与forEach()遍历

let a = document.querySelectorAll('.wp-block-button__link');
a.forEach((i) => i.href = "mydomain.com/get/?url=" + i.href);
<a class="wp-block-button__link has-background has-vivid-green-cyan-background-color" href="https://github.com/pbatard/rufus/releases/download/v3.5/rufus-3.5.exe" rel="nofollow noopener noreferrer">Download (Installer)</a>
<a class="wp-block-button__link has-background has-vivid-green-cyan-background-color" href="https://github.com/pbatard/rufus/releases/download/v3.5/rufus-3.5p.exe" rel="nofollow noopener noreferrer">Download (Portable)</a>