0

I have seen the post How to update (append to) an href in jquery? , but it doesn't seem like the answer can help at my case.

I am currently using a plugin(easytab) to create a few different tab and every tab contains a tag like <a id="tabopen" href="www.text.com/custom/questions/ask/">

<a id="tabopen" href="www.text.com/default/questions/ask/">

and for some reason I have a button which append some extra path to all the href in order to redirect user to the right place.

I have tried to use

$("a#tab1").each(function() {
   var _href = $(this).attr("href"); 
   $(this).attr("href", _href + 'startDate=20160121?endDate=20160212');
});

but instead append the 'startDate=20160121?endDate=20160212' it replace everything to www.text.com/custom/questions/ask/startDate=20160121?endDate=20160212 , which is not right, how should i fix it?

Update 1: I am sorry that i have provide wrong description at, the ids are actually the same in the plugin.

<a id="tabopen" href="www.text.com/custom/questions/ask/">

<a id="tabopen" href="www.text.com/default/questions/ask/">

Community
  • 1
  • 1
Anson Aştepta
  • 1,125
  • 2
  • 14
  • 38

1 Answers1

4

$("a#tab1") selects a single <a> element having ID as tab1. To change the href attribute of a single element there is no need of each.

var href = $('a#tab1').attr('href') + '?startDate=20160121&endDate=20160212';
$('a#tab1').attr('href', href);

If having multiple elements with same ID, ID should be unique.

To select all the elements whose ID starts with tab, you can use attribute start with selector. I'll suggest to use a unique class on them.

To change the href attribute value of all the matched elements .attr(attributeName, function) with callback function can be used.

$('a[id^="tab"]').attr('href', function(i, oldHref) {
    return oldHref + '?startDate=20160121&endDate=20160212';
});

As said by @charlietfl in the comment, the querystring format should be as follow

'?startDate=20160121&endDate=20160212'
 ^                  ^

Update:

Saying again, ID should be unique., you can use class instead of ID for similar purpose elements.

Change the markup to use class

<a class="tabopen" href="www.text.com/custom/questions/ask/">

<a class="tabopen" href="www.text.com/default/questions/ask/">

And then use the selector

$('.tabopen').something...

BAD PRACTICE:

If you can't change the markup(auto-generated markup by some plugin), you can use attribute value selector to select all elements having same ID

$('a[id="tabopen"]').something...
Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179