1

I've got a pretty straight forward question, how do I append GET values to the end of every anchor href on a page?

For example, you type in google.com?label=12&id=12

So whatever comes in, I just want to make sure that I'm appending "?label=12&id=12" to the end of every single href in an anchor tag on the page. There is an easy way to do this right? Thanks everyone! :)

Zach Broniszewski
  • 252
  • 1
  • 2
  • 13

1 Answers1

2

You can get all the anchors on the page with

var links = document.getElementsByTagName('a');

then iterate through them adding your arguments

for(var i = 0; i< links.length; i++){
    links[i].href = links[i].href + "?label=12&id=12"
}

You may have to do some work to format the parameters correctly to avoid having ?existing=value?label12&id=2

Bill H
  • 470
  • 1
  • 6
  • 12
  • 1
    Could I include PHP variables to concatenate instead of a defined string? Or is that impossible to do in JavaScript? – Zach Broniszewski May 19 '17 at 19:26
  • It's possible, but significantly different than doing it in JS. In JS, the above code would be triggered by something like a body.onLoad(). In PHP, you would be doing it server side before sending the page to the client. However the links are generated, you would need to set it up something like this: (please forgive my rusty php) `link text` This may help more: http://stackoverflow.com/questions/11480763/how-to-get-parameters-from-a-url-string – Bill H May 20 '17 at 20:57
  • 1
    What I actually did was store certain GET values in local variables, and then at the end of every single href on the page, I would put for example: href="google.com?= $label; ?>" I had to do this to so many links in the HTML that, I started to think there was a way to do it in one short local code. Does this help you understand more why I asked the question? – Zach Broniszewski May 21 '17 at 06:54
  • Yeah, that makes a lot of sense. If the problem you're having is that you keep needing to change the args you could create a LinkBuilder object that you initialize with a map of arguments to append and then pass different base urls wherever you need to use it. – Bill H May 22 '17 at 13:13