khurrum qureshi
khurrum qureshi

Reputation: 925

How to get href attribute using jquery?

<table class="table1">
    <tbody>        
       <tr class="tablerow1"> 
            <td valign="top"> 
              <strong> 
              <a href="http://www.wineweb.com/scripts/wineryPg.cfm/11094/Aan-de-Doorns-Co%2Dop/" target="_top">Aan de Doorns Co-op </a> </strong> </td></tr>
    </tbody>
</table>

It's a sample html there are multiple rows with multiple cells in actuall html that's how i am doing

$('table.table1').each(function(k, elem) {
                    $(this).find('tr').each(function(j, elem){
                        $(this).find('td').each(function(i,elem){
                            console.log($(this).find('strong a').attr('href'));
                        })
                    })
                });

but I am unable to get href through this method.

Upvotes: 3

Views: 6829

Answers (5)

nirazul
nirazul

Reputation: 3955

You can simplify your code dramatically:

$('table.table1 tr td a').each(function(idx, elem) {
    console.log($(this).attr('href'));
});

Upvotes: 1

omma2289
omma2289

Reputation: 54629

$('.table1 strong a').each(function() {
    console.log(this.href);
});

Upvotes: 2

sa77
sa77

Reputation: 3603

you can add a class to the a tag like this:

<a class="link" href="your_url" target="_top">Aan de Doorns Co-op </a>

then use the class in your jquery snippet like this:

console.log($(this).find('.link').attr('href'));

i've created a fiddle for this..hope it helps

fiddle here

Upvotes: 0

Am&#233;rico Duarte
Am&#233;rico Duarte

Reputation: 573

Use the find method (is more efficient).

$('.table1').find('a').each(function() {
    console.log($(this).attr('href'));
}

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

You can use the map method and avoid nested $.each statements.

    var hrefs = $('table.table1 tr td a').map(function() {
        return this.href;
    }).get();

   console.log(hrefs.join(','))

Check Fiddle

Upvotes: 4

Related Questions