Is there an “exists” function for jQuery?

2018-12-31 00:10发布

How can I check the existence of an element in 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?

30条回答
冷夜・残月
2楼-- · 2018-12-31 00:49

How about:

function exists(selector) {
    return $(selector).length;
}

if (exists(selector)) {
    // do something
}

It's very minimal and saves you having to enclose the selector with $() every time.

查看更多
牵手、夕阳
3楼-- · 2018-12-31 00:50

You can use this:

// if element exists
if($('selector').length){ /* do something */ }

// if element does not exist
if(!$('selector').length){ /* do something */ }
查看更多
春风洒进眼中
4楼-- · 2018-12-31 00:51

You can use:

if ($(selector).is('*')) {
  // Do something
}

A little more elegant, perhaps.

查看更多
浮光初槿花落
5楼-- · 2018-12-31 00:53

No need for jQuery

if(document.querySelector('.a-class')) {
  // do something
}
查看更多
春风洒进眼中
6楼-- · 2018-12-31 00:54

I had a case where I wanted to see if an object exists inside of another so I added something to the first answer to check for a selector inside the selector..

// Checks if an object exists.
// Usage:
//
//     $(selector).exists()
//
// Or:
// 
//     $(selector).exists(anotherSelector);
jQuery.fn.exists = function(selector) {
    return selector ? this.find(selector).length : this.length;
};
查看更多
何处买醉
7楼-- · 2018-12-31 00:56

You can save a few bytes by writing:

if ($(selector)[0]) { ... }

This works because each jQuery object also masquerades as an array, so we can use the array dereferencing operator to get the first item from the array. It returns undefined if there is no item at the specified index.

查看更多
登录 后发表回答