skip to Main Content

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

Answers


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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search