Search code examples
jqueryappendhrefattr

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!


Solution

  • 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);