Add parameter at end of link with jQuery

Asked

Viewed 985 times

1

Guys, I’m trying to take some specific URL’s on a page, and add a parameter at the end of the link, but I’m not succeeding, because it returns the object instead of the link string + the parameter.

I made a very simple example of the code:

var links = jQuery('a[href*="google.com"]');
links.attr('href', links + 'parametros_adicionais');

The execution of this code returns me the URL with this parameter at the end [Object%20Object]test

I wonder if you can help me?

2 answers

1

Links is an object that contains all the elements, you must go through the a[href*="google.com"] and change one at a time.

var param = 'SoUmParametro';
var src;
var links = jQuery('a[href*="google.com"]');
links.each(function() {
   src = $(this).prop('href');
   $(this).prop('href', src+param);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a href="http://google.com">link1</a>
<a href="http://google.com">link2</a>

  • You saved my face, and I’ve learned to use jQuery better. !

  • @thierryrenematos of nothing, do not worry about that we’ve all had these doubts

1

The right thing would be:

var links = jQuery('a[href*="google.com"]');
links.attr('href', links.attr('href') + 'parametros_adicionais');

Remembering that code with Jquery should always be inside a "ready":

    $(document).ready(function(){
       var links = jQuery('a[href*="google.com"]');
       links.attr('href', links.attr('href') + 'parametros_adicionais');
    })

Browser other questions tagged

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