2

Hi I am in process of learning jQuery. I was practicing some examples from the book reading about attr(), removeAttr(), each() functions. I decided to try different tasks and one of them was to change href attribute for a list of links( like 4 or 5 in the list), but I needed the value to be different for each link.

Here are my links:

<h1>My Favorite Shopping List!</h1>
<a href="https://www.google.com" target="_blank">Google!</a>
<a href="https://www.yahoo.com"  target="_blank">Yahoo!</a>
<a href="https://www.ebay.com" target="_blank">Ebay!</a>
<a href="https://www.amazon.com" target="_blank">Amazon</a>

Then I can use each() and attr() functions to loop through the links and change the attribute href to value www.facebook.com for example.

$(document).ready(function() {
 $('a').each(function() {
      $(this).attr( 'href', 'http://www.facebook.com');
   });
});

the final result is:

<a href="https://www.facebook.com" target="_blank">Google!</a>
<a href="https://www.facebook.com"  target="_blank">Yahoo!</a>
<a href="https://www.facebook.com" target="_blank">Ebay!</a>
<a href="https://www.facebook.com" target="_blank">Amazon</a>

But what is the possible solution if I want different values for ech link like this:

<a href="https://www.facebook.com" target="_blank">Google!</a>
<a href="https://www.instagram.com"  target="_blank">Yahoo!</a>
<a href="https://www.pinterest.com" target="_blank">Ebay!</a>
<a href="https://www.twitter.com" target="_blank">Amazon</a>

Considering less coding!

buterfly85
  • 163
  • 3
  • 11

2 Answers2

0

You can also use .prop instead of .attr. Difference between .prop & .attr

$(document).ready(function() {
var linksArray = ["https://www.facebook.com", "https://www.instagram.com"] //all links
 $('a').each(function(i,v) {
      $(this).prop( 'href', linksArray[i]);
   });
});
Community
  • 1
  • 1
vinayakj
  • 5,591
  • 3
  • 28
  • 48
0

Say you have an array with your different urls, then use index in each callback function to apply successively each url:

var urls = [
  'https://www.facebook.com',
  'https://www.instagram.com',
  'https://www.pinterest.com',
  'https://www.twitter.com'
];
$(document).ready(function(index) {
  $('a').each(function() {
      $(this).attr('href', urls[index]);
   });
});
cFreed
  • 4,404
  • 1
  • 23
  • 33