0

I don't know how to phrase this question better, so a quick snippet of my code should explain what I want:

$("tr").each(function(){
    if($(this).find("img[src='https://example.com/img.png']")){
        console.log($(this).find("a.myClass").text());
    }
});

I have a table with many rows in it (hundreds), and i'm trying to indentify the correct row by seeing if it has a certain image inside of it. After the row is indentified, it looks for a link using its class as the selector and then prints out its text content.

The problem is that the code above doesn't work, and I can't figure out why. It prints out text from table rows that don't have the correct image

  • 2
    jQuery object will always evalutes to `truthy` thus its _prints out text from table rows that don't have the correct image_. If you want to check existense of image check `length` property i.e. `if($(this).find("img[src='https://example.com/img.png']").length){ }` – Satpal Jun 15 '18 at 10:10
  • Post HTML code here to show where is image and link. – Alex S. Jun 15 '18 at 10:13
  • Can you please show your HTML code for better solution – Abhay Prince Jun 15 '18 at 10:18

1 Answers1

0

To enter the body of the if statement it has to evaluate to true. Use this

$("tr").each(function(){
if($(this).find("img[src='https://example.com/img.png']").length != 0){
    console.log($(this).find("a.myClass").text());
}
});
Ivaylo
  • 467
  • 6
  • 19