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
)