-3

I have several anchor tags on a page with the same id of 'hrefCompare'. I need to dynamically set the value of the href attribute on ALL of these a tags.

I am currently trying to do this:

$("#hrefCompare").attr("href", "foobar.com");

However, this only sets the very first anchor tag with that ID. there's 7 more on this page with the same id of 'hrefCompare'. How can I set all of the href values with that ID?

PSL
  • 122,084
  • 19
  • 250
  • 241
dferraro
  • 6,115
  • 11
  • 45
  • 68

3 Answers3

7

id must be unique, in this case I advice you to use class, which should work flawlessly:

$(".hrefCompare").attr("href", "foobar.com");

<a href="#" class="hrefCompare">a</b>
<a href="#" class="hrefCompare">b</b>
Zbigniew
  • 26,284
  • 6
  • 55
  • 64
1

You cannot do this with IDs (they are unique), try using the same css class for all the elements you want (doesn't matter if this class does not exist).

HTML:

<a href="javascript:void(0);" class="hrefCompare">text1</a>
<a href="javascript:void(0);" class="hrefCompare">text2</a>

Please avoid using # in href attributes (if you care about behaviors). Read this to know why: Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

Then:

For older jQuery versions use .attr(..) otherwise use .prop(..)

$('.hrefCompare').prop('href', 'http://www.foobar.com');

Finally:

1) To assign the same url to every href attribute of an anchor element, do the following:

$('.hrefCompare').map(function(i, v){ return $(this).prop('href', 'http://www.foobar.com'); });

2) To assign different urls to every href attributes of the anchors according to their possitions (like an array - starting from zero -), do the following:

$('.hrefCompare').map(function(i, v){ 
    if(i === 0) url = 'http://www.stackoverflow.com';
    if(i === 1) url = 'http://www.foobar.com';
    return $(this).prop('href', url);
});

Using this way...

first anchor, position 0: (text1 => if clicked => will redirect to stackoverflow)

second anchor, position 1: (text2 => if clicked => will redirect to foobar)

Community
  • 1
  • 1
Oscar Jara
  • 13,805
  • 10
  • 60
  • 93
1

Ids must be unique in a DOM. try to use a class name and use jquery each function

$('a').each(function(k,v){
  $(v).attr('href','mylink');
});
Anirudhan J
  • 2,012
  • 6
  • 26
  • 45