Is there an “exists” function for jQuery?
How can I check the existence of an element in jQuery?
我該如何在jQuery檢查/判斷某個元素是否存在
The current code that I have is this:
if ($(selector).length > 0) {
// Do something
}
Is there a more elegant way to approach this? Perhaps a plugin or a function?
有沒有更加簡潔的方式能達到一樣的效果呢?
In JavaScript, everything is 'truthy' or 'falsy', and for numbers 0 (and NaN) means false, everything else true. So you could write:
在JavaScript中所有東西都只有是與否,而數字0(與NaN)是屬於false的,其他都屬於true,所以你只需要這樣寫:
if ($(selector).length)
You don't need that >0 part.
你不需要 >0 的部分
或者jQuery的部分:
jQuery.fn.exists = function(){ return this.length > 0; }
if ($(selector).exists()) {
// Do something
}