Reputation: 283
I need to create a function that gets the url from one link and applies it to another within the same div. I can get it to loop through but it always assigns the last variable to all of the links.
Here is the code :
$.fn.getLink = function() {
$('a.firstlink').each(function(){
var linkHref= $(this).attr('href');
('a.secondlink').attr('href', linkHref)
});
}
$('div.containing-links').each(function(){
$(this).getLink();
});
Help appreciated.
Thanks for your quick answers, to make it a bit simpler here is the code that adds the link correctly but repeats the last href variable to all of them:
$('a.firstlink').each(function(){
var linkHref= $(this).attr('href');
$('a.secondlink').attr('href', linkHref);
});
How can I apply this to each one at a time?
Upvotes: 2
Views: 1341
Reputation: 18964
Your problem is that $('a.secondlink')
grabs all of the links on the page. just because it is inside the each loop does not mean it is scoped to anything.
Just change $('a.secondlink').attr('href', linkHref)
to look something like $(this).siblings('a.secondlink').attr('href', linkHref);
Upvotes: 2
Reputation: 236022
I don't think this is a good spot to write a plugin. You should do it straightforward in your .each() loop
.
$('div.containing-links').each(function(){
var $self = $(this),
$first = $self.find('a.firstlink'),
$second = $self.find('a.secondlink');
if( $first.length && $second.length )
$second[0].href = $first[0].href;
});
Upvotes: 1