Check if element exists

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

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.


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

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

链接地址: http://www.djcxy.com/p/14674.html

上一篇: 如何检查页面上是否存在具有ID的对象?

下一篇: 检查元素是否存在