Concatenate string to all href of the page

Asked

Viewed 250 times

0

I wonder if there is a function in jQuery that can concatenate to the page hrefs a string.

My page behaves in a different way if my url contains #es or #pr, so I wanted to keep this comment at the end of each link.

Example:

<a href="/pagina/">Página</a>

would become, if the comment #pr is at the url

<a href="/pagina/#pr">Página</a>

But I wanted to do it with all the links on the page.

A function that captures all href'and that I can put them in their proper places.

2 answers

1


To change the value can be something like:

$('a').each(function(index,item){
  var link = $(this).prop('href') + "#pr";
  $(this).prop('href', link);  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="/pagina/">Página 1</a>
<a href="/pagina/">Página 2</a>
<a href="/pagina/">Página 3</a>

This way it is possible to iterate through all links and change the property of each one.

0

I did a brief search and found this.

You can use this Jquery code :$(window).on('hashchange', function(e){}); It detects change in the url, you can capture the new url and concatenate your code before the "original url". Thus adding your tags.

Topic with Jsfiddle : Topic Stackoverflow

Hug and success on your journey.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.