31

Possible Duplicates:
Is there an “exists” function for jQuery
jQuery determining if element exists on page

if(tr) is returning true when tr is not an element, how do I check whether it's an element that exists?

var tr = $('#parts-table .no-data').parent();
$('.delete', row).bind('click', function (e) {
  that.delete(e.currentTarget);
});
console.log(tr);
if (tr) //returns true when it shouldn't
Community
  • 1
  • 1
Ben
  • 60,438
  • 111
  • 314
  • 488

5 Answers5

36

Check its length property:

if(tr.length) {
    // exists
}

if(tr) always evaluates to true because a jQuery object, or any JavaScript Object for that matter, is always truthy.

karim79
  • 339,989
  • 67
  • 413
  • 406
8

I always add this little jQuery snippet at the beginning of my JS files

jQuery.fn.exists = function(){return jQuery(this).length>0;}

This uses the same approach many here have suggested, but it also allows you to access whether or not an object exists like this:

if ( $('#toolbar').exists() ){
    $('#toolbar').load(..., function(){...});
    //etc...
}
Dutchie432
  • 28,798
  • 20
  • 92
  • 109
3

That's because tr is a jQuery object, which is truthy (even when the jQuery object is empty). Use if (tr.length) instead, which will be true when length is not zero, false when it is zero. Or alternately, if (tr[0]).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

How about:

if (tr.size() == 0) 
Mark Robinson
  • 13,128
  • 13
  • 63
  • 81
1

try this

var tr = $('#parts-table .no-data').parent().length;
Harish
  • 2,311
  • 4
  • 23
  • 28