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
8

5 Answers 5

37

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.

0
9

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...
}
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]).

1

How about:

if (tr.size() == 0) 
1

try this

var tr = $('#parts-table .no-data').parent().length;

Not the answer you're looking for? Browse other questions tagged or ask your own question.