iGallina
iGallina

Reputation: 610

jQuery selecting returns undefined

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);
});

Upvotes: 0

Views: 70

Answers (2)

LcSalazar
LcSalazar

Reputation: 16841

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!!!
});

Upvotes: 2

flowstoneknight
flowstoneknight

Reputation: 1236

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

Upvotes: 3

Related Questions