Making all links go to the same place - a bit of fun

Hi folks,

Just playing around here, I am trying to get all links to go to the same place heres my code:

	const fixedWidth = document.querySelectorAll('a');
			console.log(fixedWidth);

			for (var i = 0; i < fixedWidth.length; i++) {
				  fixedWidth[i].addEventListener('click', function() {
				   console.log('Clicked');
				   window.location.href	 = "https://www.bbc.co.uk"
				  });
				}

It doesn’t seem to work - how would one do this?
Cheers :slight_smile:

change the link to another website and it will work.
Example:
window.location.href = "https://www.nichepursuits.com/";

1 Like

Your code does seem to work, after running it and clicking in whatever <a> in a page it is redirecting.

There is a problem though, when the element <a> already has a href attribute to somewhere it will redirect to the href and to your url (in your example, bbc).

To fight this instead of assigning a new event “click” we can instead of the native functionality of the <a> tag and instead assign the value we want for the attribute href like so

const fixedWidth = document.querySelectorAll('a');

for (var i = 0; i < fixedWidth.length; i++) {
	fixedWidth[i].setAttribute('href', 'https://www.bbc.co.uk');
}

This will change all of the <a>'s of a page to bbc regardless of them already having the href already or not and will not have the problem of double redirect :grinning:

Note Mind you that if the page where you’re doing this has a “click” event on an <a> it will happen the same problem of double redirect making your href execute first and then the “click” event that is on the page

1 Like

Thanks for this mate! This is what I was looking for. So I need to just change the

setAttribute

and I am all good, cheers!!!

1 Like