Search code examples
jqueryhref

Get href from link and attach it to another link


I actually have working code for this problem, but I think it's probably not very efficient. I think I could probably combine it into one, but my knowledge of JS is still limited enough that I'm not sure how to do it.

The problem: I have 3 slider divs on the homepage. Each div has an H5 title tag wrapped in an unpopulated <a> tag. So I need to pull the href from each div's .slideshow-button and apply it to the h5 tag. (Weird problem, but just go with it.)

The (inefficient? but working) solution:

$('.homepage-slideshow:first-child .title-controls a').attr('href', $('.homepage-slideshow:first-child .slideshow-buttons a').attr('href')); 
$('.homepage-slideshow:nth-child(2) .title-controls a').attr('href', $('.homepage-slideshow:nth-child(2) .slideshow-buttons a').attr('href')); 
$('.homepage-slideshow:nth-child(3) .title-controls a').attr('href', $('.homepage-slideshow:nth-child(3) .slideshow-buttons a').attr('href')); 

Can I combine these into one, so I don't have to do it 3 separate times?


Solution

  • Try this (assuming you need to change links within each of your .homepage-slideshow):

    $('.homepage-slideshow').each(function () {
       var $this = $(this);
       var href = $this.find('.slideshow-buttons a').attr('href');
       $this.find('.title-controls a').attr('href', href);
    });