Juan Carcelen
Juan Carcelen

Reputation: 3

JQuery. Copy link attribute to a dynamic element within a div

I'm still learnig jQuery and I'm stuck trying to have each of the dynamically generated links the same URL as the previous static link within the Div. The code seems to apply the same URL (#1) to all the generated links, when on the second Div I need it to be #2.

CODE:

$(document).ready(function() {
$('.sorter > div p').append('<a class="rdm">Read More</a>');
$('a.rdm').each(function() {
    var lnk = $('.sorter > div').find('a').attr('href');
    $(this).attr('href', '' + lnk);
});
});

HTML:

<div class="sorter">
<div><a href="#1">link A</a><p>some text </p></div><br /><br />
<div><a href="#2">link B</a><p>some text </p></div>
</div>

Many thanks for your help!

Upvotes: 0

Views: 3918

Answers (3)

Patrick Lewis
Patrick Lewis

Reputation: 2141

Using scoped selectors helps you deal with each div individually. Here's a jsfiddle with a working solution: http://jsfiddle.net/tuAUb/

$(document).ready(function() {
    $('.sorter > div').each(function() {
        $('p', this).append('<a class="rdm">Read More</a>');
        var lnk = $(this).find('a').attr('href');
        $('a.rdm', this).attr('href', lnk);
    });
});

Upvotes: 2

Jai
Jai

Reputation: 74738

Oh i think you need this one: http://jsfiddle.net/GSgz5/

 var lnk = $(this).parent().siblings('a').attr('href'); //<--get href this way
 $(this).attr('href', lnk);

Upvotes: -1

John Kalberer
John Kalberer

Reputation: 5800

Try this. When you do the each I use the index of the anchor to generate it's href:

$(document).ready(function() {
    $('.sorter > div p').append('<a class="rdm">Read More</a>');
    $('a.rdm').each(function(i) {
        $(this).attr('href', '#' + (i + 1));
    });
});

Upvotes: 0

Related Questions