Get href attribute on jQuery

BILL picture BILL · Dec 27, 2011 · Viewed 138.1k times · Source

I have some table rows

<tr class="b_row">
    <td>
        <div class="cpt">
            <h2>
                <a href="/ref/ref/1.html">example</a>
            </h2>
        </div>
    </td>
</tr>

<!--more elements -->

<tr class="b_row">
    <td>
        <div class="cpt">
            <h2>
                <a href="/ref/two/23.html">example N</a>
            </h2>
        </div>
    </td>
</tr>

I need to get hyperlinks in attribute. I use this script

function openAll()
{
    $("tr.b_row").each(function(){
    var a_href = $('div.cpt').find('h2 a').attr('href');
    alert ("Href is: " + a_href);
}

Problem: variable a_href is always / ref/ref/1.html

Answer

M. Hryszczyk picture M. Hryszczyk · Dec 27, 2011

In loop you should refer to the current procceded element, so write:

var a_href = $(this).find('div.cpt h2 a').attr('href');