R.M. Reza
R.M. Reza

Reputation: 999

Change All URLs with a Specific ID Using Javascript

I have an html code to download files like this:

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

I want all the URLs in the class="wp-block-button__link tag to change like this:

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

I am currently changing it using Javascript like this:

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

The javascript code that I use now can only change one URL, I want to change all the URLs in the class="wp-block-button__link" tag.

How do I make the javascript code I use change all URLs in the tag class="wp-block-button__link", not just one URL?

Upvotes: 0

Views: 54

Answers (2)

User863
User863

Reputation: 20039

Using document.querySelectorAll() and loop through it with 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>

Upvotes: 1

Jack Bashford
Jack Bashford

Reputation: 44087

Use querySelectorAll and forEach:

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

Upvotes: 2

Related Questions