0

I am not sure why this is happening, I listed two ways one that the code works and another that doesn't. I want to get the value inside de the EACH with THIS if this is possible so I can alter the value, but I can olny select them from outside doing an each for all IMG, which makes me loose the reference for the TD associated with that IMG.

http://jsfiddle.net/4w8030th/1/

// Cannot retrieve SRC inside IMG tag
$.each($('tr.infraTrClara'), function () {
    // Post-It
    var postit = $(this).children('td:nth-child(2)').select('img');
    postit_src = $(postit).attr('src');
    alert(postit_src);
});

// Can retrieve SRC inside IMG tag
$.each($('tr.infraTrClara td:nth-child(2) img'), function () {
    // Post-It
    var postit = $(this).attr('src');
    alert(postit);
});
Keavon
  • 6,837
  • 9
  • 51
  • 79
iGallina
  • 590
  • 5
  • 11

2 Answers2

3

.select() is an event listener binding method, similar to .click(). You probably want a .children() there to achieve the same behavior.

flowstoneknight
  • 1,248
  • 1
  • 7
  • 6
2

The suitable method for this case is .find() instead of .children() or .select().

Then, since it will be a multiple result, instead of setting it to a variable, perform the .each() on it too:

http://jsfiddle.net/4w8030th/3/

$.each($('tr.infraTrClara'), function () {
    // Post-It
    $(this).find('td:nth-child(2)').find('img').each(function() {
        postit_src = $(this).attr('src');
        alert(postit_src);
    });
});

EDIT

Kevin made a good point at the comments. I was assuming that you needed a solution different from the second code you posted (that is working), for another reason...

But, you've mentioned that you didn't want to

lose the reference for the TD associated with that IMG.

So, if all you wanted was to manipulate the td, use your second code and call it using parent():

$.each($('tr.infraTrClara td:nth-child(2) img'), function () {
    // Post-It
    var postit = $(this).attr('src');
    alert(postit);

    var td = $(this).parent(); //HERE!!!
});
LcSalazar
  • 16,524
  • 3
  • 37
  • 69
  • Why is find more suitable than children? Did he include html somewhere that suggests he has more than just an img in the cell? I'd argue his own second attempt is better than using find or children. – Kevin B Sep 04 '14 at 18:08
  • Maybe I've expressed wrongly... Suitable is not the word, but `find` is faster than `children`. http://stackoverflow.com/questions/648004/what-is-fastest-children-or-find-in-jquery – LcSalazar Sep 04 '14 at 18:11