Reputation: 6008
<section class="photos">
<table>
<tr>
<td><a href="/a"><img src="b.jpg" /></a></td>
<td><a href="/a"><img src="b.jpg" /></a></td>
<td><a href="/a"><img src="b.jpg" /></a></td>
</tr>
<tr>
<td><a href="/a"><img src="b.jpg" /></a></td>
<td><a href="/a"><img src="b.jpg" /></a></td>
</tr>
</table>
</section>
And then I am trying to iterate through each to return the link href and the image src.
$(".photos td").each(function (index, value) {
console.log(value.a.attr('href'));
console.log(value.img.attr('src'));
});
The above pseudo-broken-code doesn't unfortunately work. Any ideas?
Upvotes: 0
Views: 141
Reputation: 28608
Try this:
$(".photos td").each(function (index, value) {
console.log($(this).find('a').attr('href'));
console.log($(this).find('img').attr('src'));
});
Upvotes: 1
Reputation: 2279
Adam already gave the answer, but since I was typing it... try this: (the only difference is in the traversal part, since Adam uses "this" while I use "value" (which are the same).
$(".photos td").each(function (index, value) {
console.log($('a', value).attr('href'));
console.log($('img', value).attr('src'));
});
Don't forget that value represents a dom element (and not a jQuery element), and attr() is a jQuery method that works only for jQuery objects. Also, shouldn't you be closing your tags?
Upvotes: 1
Reputation:
You can't run jQuery methods on value
, since it's just a DOM node. Create a jQuery object out of it first (I prefer this
to the value
argument, but they're the same in this case):
$('.photos td').each(function(){
console.log( $(this).find('a').attr('href') );
console.log( $(this).find('img').attr('src') );
});
Upvotes: 3