tags:

views:

23

answers:

1

So for example, I have a list and I need to extract the hrefs from it:

<ul class="list1">
<li><a href="link1">Link1</a></li>
<li><a href="link2">Link2</a></li>
<li><a href="link3">Link3</a></li>
</ul>

BTW, this forums spam protection is not letting me put any more hyper links which is why the code above is semantically incorrect.

And apply those hrefs to the list below in order

<ul class="list2">
<li><a>Link1</a></li>
<li><a>Link2</a></li>
<li><a>Link3</a></li>
</ul>

It is to be dynamic (meaning as many hrefs in the first list as I want), so I'm not looking to use eq or nth, I've gotten this far by reading help in this forum, but am unclear on how to continue with applying the hrefs to the second list:

var hrefs = '';

$('ul#direction-fade-slider li a.url').each(function(idx, item) {  
  hrefs += item.href + '\n';  
});

Any help would be greatly appreciated! Thanks!

+3  A: 

You can do it using a .each() loop like this:

var anchors = $("ul.list2 a");
$("ul.list1 a").each(function(i) {
   anchors.get(i).href = this.href;
});

All this is doing it getting the destination anchors (or you can reverse it...), looping through the <a> elements in order and setting the href on the corresponding one at the same index in the destination .list2.

Alternatively, you could use .attr() like this:

var source = $("ul.list1 a");
$("ul.list2 a").attr('href', function(i) {
   return source.eq(i).attr('href');
});
Nick Craver
Wow, I incredibly over thought this entire approach. I have literally searched and tried everything and I can't believe it was this simple. Nick, much appreciated for the advice. I'm liking the fact that this forum is thoroughly indexed by Google so that others can make use of these approaches. BTW, I used your second approach and it did exactly what I was looking for.Thanks again!
Jim