How to update (append to) an href in jquery?

Jquery

Jquery Problem Overview


I have a list of links that all go to a google maps api.

the links already have the daddr (destination) parameter in them as static. I am using Geo-Location to find the users position and I want to add the saddr (source address) to the links once I get the data.

so basically I will need to add something like &saddr=50.1234567,-50.03452 at the tail end of all the links pointing to google maps

All the links have a class called directions-link

and from this page I have figured out how to change them:

$("a.directions-link").attr("href", "http://www.google.com/");

However I only want to append my value to the end of the href without changing what the href already is.

How can I do that?

Jquery Solutions


Solution 1 - Jquery

var _href = $("a.directions-link").attr("href");
$("a.directions-link").attr("href", _href + '&saddr=50.1234567,-50.03452');

To loop with each()

$("a.directions-link").each(function() {
   var $this = $(this);       
   var _href = $this.attr("href"); 
   $this.attr("href", _href + '&saddr=50.1234567,-50.03452');
});

Solution 2 - Jquery

jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:

$("a.directions-link").attr("href", function(i, href) {
  return href + '?q=testing';
});

That loops over all the elements too, so no need for $.each

Solution 3 - Jquery

$("a.directions-link").attr("href", $("a.directions-link").attr("href")+"...your additions...");

Solution 4 - Jquery

Here is what i tried to do to add parameter in the url which contain the specific character in the url.

jQuery('a[href*="google.com"]').attr('href', function(i,href) {
	    //jquery date addition
       	var requiredDate = new Date();
		var numberOfDaysToAdd = 60;
		requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd); 
		//var convertedDate  = requiredDate.format('d-M-Y');
		//var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
		//console.log(requiredDate);

		var month 	= requiredDate.getMonth()+1;
		var day 	= requiredDate.getDate();

		var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
		//

Working Example Click

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJD IsaacksView Question on Stackoverflow
Solution 1 - JqueryGabeView Answer on Stackoverflow
Solution 2 - JqueryzaiusView Answer on Stackoverflow
Solution 3 - JqueryDiodeus - James MacFarlaneView Answer on Stackoverflow
Solution 4 - JqueryBikram ShresthaView Answer on Stackoverflow