0
<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?

James
  • 5,942
  • 15
  • 48
  • 72

3 Answers3

3

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') );
});
Annika Backstrom
  • 13,937
  • 6
  • 46
  • 52
1

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?

Marcelo Zabani
  • 2,139
  • 19
  • 27
1

Try this:

$(".photos td").each(function (index, value) {
    console.log($(this).find('a').attr('href'));
    console.log($(this).find('img').attr('src'));
});
icyrock.com
  • 27,952
  • 4
  • 66
  • 85