2

This is my fiddle of finding a text in tr.

I used

var reports = $('table#reports > tbody');
var tr1 = reports.find('tr:has(td:contains("First Name"))');

to find the text but even if the text does not exist it still alerts that it exists. To check if it exist i created an if

if (tr1) {
    alert('exist');
 } else {
    alert('not');
 }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Brownman Revival
  • 3,620
  • 9
  • 31
  • 69

2 Answers2

2

The problem is .find()(infact all traversing methods) return a jQuery object which is always truthy, so your condition will always be true.

If you want to see whether the selector found any matches then you can check the length property of the jQuery object which will give the number of dom element references returned by the selector, so if there are no matched elements it will return 0

so

if (tr1.length) {
    alert('exist');
} else {
    alert('not');
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Check if tr1 is not undefined and length is greater than 1

Akshay
  • 530
  • 7
  • 20