user3927582
user3927582

Reputation: 189

jQuery adding auto link to href attribute

HTML:

< p class="link-panel ">http:..www.google.com< /p ><br>
< a target="blank" href="">GO< /a>

jQuery:

var linkVal = new Array();
    $('.link-panel').each(function(index){
        linkVal[index] = $(this).text();
    });

$('a').each(function(){
    $(this).attr("href", linkVal);
});

I'm trying to get the text value from the P tag and append it to the href attribute in the link. I can do this for one, but I can't seem to work out how to make this work when there is more than one URL?

Thanks

Upvotes: 1

Views: 128

Answers (1)

adeneo
adeneo

Reputation: 318302

You can iterate over the anchors and get the text from the previous paragraph

$('a').attr('href', function() {
    return $(this).prev('p').text();
});

or iterate over paragraphs and set the href for the following anchor

$('.link-panel').each(function() {
    $(this).next('a').attr('href', $(this).text());
});

Upvotes: 1

Related Questions