How to replace href of all anchor tags in a bookmarklet?

62 Views Asked by At

I'm trying to make a bookmarklet that changes every link on a page to "https://www.youtube.com/watch?v=dQw4w9WgXcQ" and iv'e gotten this far:

a.forEach(function(a){
a.href = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";
});
alert("done.");

The html editor shows that the href of the "a" tag has changed but won't go to the new link. Im using this bookmarklet on websites I don't own, so I can't add classes or id's.

If you are going to close the question due to it being a duplicate, please tell me the duplicate.

2

There are 2 best solutions below

1
joe-bro On BEST ANSWER

Try:

javascript:var url="https://github.com/"; var all_links = document.getElementsByTagName("a");for (var link_num = 0; link_num < all_links.length; link_num++) {var link = all_links[link_num];link.href = url;};alert("changed " + link_num + " links")

Change the url variable to whatever you want and it should change all links to that and alert the amount of links changed.

0
cssyphus On

What you want to do might be more easily done via the Tampermonkey browser extension.

Your code might look like this:

// ==UserScript==
// @name         Change all A Tags
// @namespace    MyNameSpaceItsMe
// @match        https://yourdomain.com/*
// @grant        none
// ==/UserScript==

'use strict';
const allA = document.querySelectorAll('a');

allA.forEach( (a) => {
    a.setAttribute("href", "https://www.youtube.com/watch?v=dQw4w9WgXcQ");
});

Here is some information about Tampermonkey:

What is Tampermonkey and what can it do for me

Some tips for getting started with Tampermonkey

Where to find Tampermonkey in the Chrome Web Store

Video tutorial for getting started with Tampermonkey

Another short video re getting started with Tampermonkey