stckvrw
stckvrw

Reputation: 1801

Add certain end to all the internal links on the page

I need some simple code on pure JavaScript (NOT jQuery!) that will add certain end to all the internal links on a page (i.e. to all the links that contain website domain in its href attribute), something like:

var pagelinks = document.getElementsByTagName('a');
for(var i in pagelinks) {
  if(pagelinks.getAttribute('href').indexOf(document.domain) != -1) {
    pagelinks[i].setAttribute('href',currenthref+'my_end');
  }
}

!!! NOTE: it's not working script — it's only "something like" what I need

For example the internal links on a page are:

<a href="http//mysite.com/showcase">Showcase</a>
<a href="http//mysite.com/contacts">Contacts</a>
...

I need

<a href="http//mysite.com/showcase?my_end">Showcase</a>
<a href="http//mysite.com/contacts?my_end">Contacts</a>
...

Upvotes: 0

Views: 63

Answers (1)

Chrillewoodz
Chrillewoodz

Reputation: 28338

If I understand your question correct this is what you want:

var domain = 'www.youtube.com';

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

for (var i = 0; i < pagelinks.length; i++) {

  var current = pagelinks[i].getAttribute('href');

  if (current.indexOf(domain) !== -1) {
    pagelinks[i].setAttribute('href', current + '?my_end');
  }
}

Updated fiddle: https://jsfiddle.net/cm69qmnL/6/

You have to specify the domain you want to check the href attributes against and then run a loop which checks each anchor's href attribute, checks it against the specified domain and updated the href if the domain exists in current.

Upvotes: 2

Related Questions