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:38

Checking for existence of an element is documented neatly in the official jQuery website itself!

Use the .length property of the jQuery collection returned by your selector:

if ($("#myDiv").length) {
    $("#myDiv").show();
}

Note that it isn't always necessary to test whether an element exists. The following code will show the element if it exists, and do nothing (with no errors) if it does not:

$("#myDiv").show();
查看更多
只靠听说
3楼-- · 2018-12-31 00:38

I just like to use plain vanilla javascript to do this.

function isExists(selector){
  return document.querySelectorAll(selector).length>0;
}
查看更多
栀子花@的思念
4楼-- · 2018-12-31 00:40

There's no need for jQuery really. With plain JavaScript it's easier and semantically correct to check for:

if(document.getElementById("myElement")) {
    //Do something...
}

If for any reason you don't want to put an id to the element, you can still use any other JavaScript method designed to access the DOM.

jQuery is really cool, but don't let pure JavaScript fall into oblivion...

查看更多
梦该遗忘
5楼-- · 2018-12-31 00:41

Is $.contains() what you want?

jQuery.contains( container, contained )

The $.contains() method returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. Otherwise, it returns false. Only element nodes are supported; if the second argument is a text or comment node, $.contains() will return false.

Note: The first argument must be a DOM element, not a jQuery object or plain JavaScript object.

查看更多
大哥的爱人
6楼-- · 2018-12-31 00:42

I have found if ($(selector).length) {} to be insufficient. It will silently break your app when selector is an empty object {}.

var $target = $({});        
console.log($target, $target.length);

// Console output:
// -------------------------------------
// [▼ Object              ] 1
//    ► __proto__: Object

My only suggestion is to perform an additional check for {}.

if ($.isEmptyObject(selector) || !$(selector).length) {
    throw new Error('Unable to work with the given selector.');
}

I'm still looking for a better solution though as this one is a bit heavy.

Edit: WARNING! This doesn't work in IE when selector is a string.

$.isEmptyObject('hello') // FALSE in Chrome and TRUE in IE
查看更多
刘海飞了
7楼-- · 2018-12-31 00:42
$(selector).length && //Do something
查看更多
登录 后发表回答