Joe Bobby
Joe Bobby

Reputation: 2811

Javascript: Forcing All Links to Goto Same URL?

i have many different links on the page and instead of changing them one by one, i want to force them all to goto the same URL using Javascript (or php if possible)

Is there a way I can define where I want all URLs to go at the top of the page? so when a user clicks any link it will goto the URL specified in javascript?

Upvotes: 0

Views: 63

Answers (2)

NightKn8
NightKn8

Reputation: 379

Like this?

const links=document.links;
Array.from(links).map((a)=>a.setAttribute("href","https://google.com"));
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="https://stackoverflow.com" target="_blank">SO</a>

seams that _blank is not working on SO but trust me: it works
Edit: Since you may wish to spare anchors on your page starting with # you can add the following if:

const links=document.links;
Array.from(links).map((a)=> (!a.getAttribute('href').match(/^\#.*/m)) ? a.setAttribute("href","https://google.com") : false);
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="https://stackoverflow.com" target="_blank">SO</a>
<a href="#C4">Chapter 4</a>

Upvotes: 1

Ahmad
Ahmad

Reputation: 1

//You can Use jquery`
$('a').attr('href','your url');
//Or JAVASCRIPT
n=getElementsByTagName('a').length
for(i=0;i<n;i++){
document.getElementsByTagName("a")[i].setAttribute("href", "your URL");
}

Upvotes: 0

Related Questions