user2890068
user2890068

Reputation: 35

Pass URL parameter to href using JavaScript

I've got some JavaScript to retrieve a URL parameter, check if the parameter called "pc" was found and if it's value is "tmgppc5" or "tmgggr1", then append to all hrefs on the page.

var pc = getQueryVariable("pc"),
url = 'http://www.thisurl.com';

// Check if the parameter called "pc" was found and if it's value is "tmgppc5" or "tmgggr1"
if (pc && pc === "tmgppc5" || "tmgggr1") {
    url += "pc=" + pc; 
}

function getQueryVariable(variable)
{
       var query = window.location.search.substring(1);
       var vars = query.split("&");
       for (var i=0;i<vars.length;i++) {
               var pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

var elements = document.getElementsByTagName('href')[0];
elements.setAttribute('href',url);

I'm using getElementsByTagName to search for all hrefs, however I get the error: uncaught type error cannot read property 'setAttribute' of undefined

Using getElementsById on a single href works, using getElementsByClassName returns the same error. What's the cause of the error? Is there an alternative? Thanks.

Upvotes: 0

Views: 307

Answers (2)

Martijn de Langh
Martijn de Langh

Reputation: 415

The tag is a for example (a link <a href=""></a>), if the links are anchors you could use getElementsByTagName('a')

Upvotes: 0

Goran.it
Goran.it

Reputation: 6299

You have 2 errors there, 1. you are searching for "href" instead of "a" and secondly you can not setAttribute on node collection, try to loop trough them :

var elements = document.getElementsByTagName('a');
// You can also use document.querySelectorAll("a")
for (var i=0; i< elements.length; i++) {
     elements[i].setAttribute('href',url);
}

Upvotes: 1

Related Questions