javascript - how to set href value on all elements with a given ID? -


i have several anchor tags on page same id of 'hrefcompare'. need dynamically set value of href attribute on of these tags.

i trying this:

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

however, sets first anchor tag id. there's 7 more on page same id of 'hrefcompare'. how can set of href values id?

you cannot ids (they unique), try using same css class elements want (doesn't matter if class 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 care behaviors). read know why: which "href" value should use 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) assign same url every href attribute of anchor element, following:

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

2) assign different urls every href attributes of anchors according possitions (like array - starting 0 -), 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 way...

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

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


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -