user5223227
user5223227

Reputation:

Add string to url on page load (javascript/jquery)

Looking to add a string to all urls in a particular div upon page load for marketing purposes, however my code does not appear to be working sadly:

$(document).ready(function() {
var trail = '?cid=marketing-string';
$("#sample-div").find('a').attr('href') + trail;
});

Desired result would be turning:

<div id="sample-div">
  <a href="http://www.example.com">
</div>

Into

<div id="sample-div">
  <a href="http://www.example.com?cid=marketing-string">
</div>

Upvotes: 0

Views: 1846

Answers (5)

Hussain Patel
Hussain Patel

Reputation: 470

Try this jquery .. I have tried in a sample MVC application

$("a[href^='http://example.com']")
   .each(function () {
       this.href = this.href.replace(/^http:\/\/example\.com/,
         "http://www.example.com?cid=marketing-string");
   });

Upvotes: 0

thedevlpr
thedevlpr

Reputation: 1101

You can easily change the selector to gather any link located throughout your page and append the text to each through this

$(document).ready(function () {
  $('#sample-div a').each(function () {
      this.href += '?cid=marketing-string';
  })
});

http://jsfiddle.net/v5w27yso/

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

You can do this using attr-attributeName-function:

$("#sample-div").find('a').attr('href', function(i, val){
    return val + trail;
});

Your code issue is that you are getting the href correctly like

$("#sample-div").find('a').attr('href');

Then concatenating trail to it correctly, but after that you are not setting it anywhere. So, that's why your code doesn't work.

FIDDLE DEMO

Upvotes: 1

Manwal
Manwal

Reputation: 23816

If you want to set attribute value you have to pass value as second parameter in attrib() function.

.attr( attributeName, value )

Consider following:

var trail = '?cid=marketing-string';
$("#sample-div").find('a').attr('href', $("#sample-div").find('a').attr('href') + trail);

Above code is equivalent to :

var trail = '?cid=marketing-string';
var url = $("#sample-div").find('a').attr('href');
$("#sample-div").find('a').attr('href', url + trail);

DEMO

Upvotes: 1

Shrinivas Shukla
Shrinivas Shukla

Reputation: 4453

Check out this fiddle

Here is the snippet.

$(document).ready(function() {
  var trail = '?cid=marketing-string';
  var original = $("#sample-div").find('a').attr('href');
  $("#sample-div").find('a').attr('href', original + trail);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sample-div">
  <a href="http://www.example.com" >Link</a>
</div>

Upvotes: 0

Related Questions