Check if item exists

Possible duplicates:
Is there a function "exists" for jQuery
jQuery determines if an element exists on a page

if(tr) returns true when tr is not an element, how to check if it is 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 
+9
javascript jquery
Jan 25 '11 at 16:14
source share
5 answers

Check its length property:

 if(tr.length) { // exists } 

if(tr) always evaluates to true because the jQuery object or any JavaScript object is always true.

+31
Jan 25 '11 at 16:15
source share

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 that many have suggested, but it also allows you to access whether or not such an object exists:

 if ( $('#toolbar').exists() ){ $('#toolbar').load(..., function(){...}); //etc... } 
+6
Jan 25 '11 at 16:26
source share

This is because tr is a jQuery object that is true (even if the jQuery object is empty). Use if (tr.length) , which will be true if length not equal to zero, false when it is zero. Or alternately, if (tr[0]) .

+2
Jan 25 '11 at 16:15
source share

What about:

 if (tr.size() == 0) 
0
Jan 25 '11 at 16:17
source share

try it

 var tr = $('#parts-table .no-data').parent().length; 
0
Jan 25 '11 at 16:23
source share



All Articles