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
In loop you should refer to the current procceded element, so write:
var a_href = $(this).find('div.cpt h2 a').attr('href');
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 find
s if you like, I left them separate to illustrate the point.)
Very simply, use this
as the context: http://api.jquery.com/jQuery/#selector-context
var a_href = $('div.cpt', this).find('h2 a').attr('href');
Which says, find 'div.cpt'
only inside this
Use this:
$(function(){
$("tr.b_row").each(function(){
var a_href = $(this).find('div.cpt h2 a').attr('href');
alert ("Href is: "+a_href);
});
});
See a working demo: http://jsfiddle.net/usmanhalalit/4Ea4k/1/
add a reference to this
, which refers to your b_row
:
$("tr.b_row").each(function(){
var a_href = $( this ).find('div.cpt h2 a').attr('href');
alert ("Href is: "+a_href);
});
Use $(this)
for get the desire element.
function openAll()
{
$("tr.b_row").each(function(){
var a_href = $(this).find('.cpt h2 a').attr('href');
alert ("Href is: "+a_href);
});
}