Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get href attribute on jQuery

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

like image 218
BILL Avatar asked Dec 27 '11 17:12

BILL


People also ask

How to find element by href jQuery?

If you want to get any element that has part of a URL in their href attribute you could use: $( 'a[href*="google.com"]' ); This will select all elements with a href that contains google.com, for example: http://google.com.

How to href in jQuery?

Answer: Use the jQuery . attr() Method You can use the jQuery . attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

What method can be used to retrieve the href attribute of an element?

Use getAttribute() to Get Href in JavaScript The Element interface's getAttribute() method returns the value of a specified attribute for the element.


2 Answers

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

var a_href = $(this).find('div.cpt h2 a').attr('href'); 
like image 177
M. Hryszczyk Avatar answered Oct 22 '22 18:10

M. Hryszczyk


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

should be

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

In the first line, your query searches the entire document. In the second, the query starts from your tr element and only gets the element underneath it. (You can combine the finds if you like, I left them separate to illustrate the point.)

like image 29
Dennis Avatar answered Oct 22 '22 17:10

Dennis