Check if element exists in jQuery [duplicate]

2018-12-31 23:28发布

This question already has an answer here:

How do I check if an element exists if the element is created by .append() method? $('elemId').length doesn't work for me.

8条回答
流年柔荑漫光年
2楼-- · 2018-12-31 23:42

If you have a class on your element, then you can try the following:

if( $('.exists_content').hasClass('exists_content') ){
 //element available
}
查看更多
临风纵饮
3楼-- · 2018-12-31 23:43

You can use native JS to test for the existence of an object:

if (document.getElementById('elemId') instanceof Object){
    // do something here
}

Don't forget, jQuery is nothing more than a sophisticated (and very useful) wrapper around native Javascript commands and properties

查看更多
人气声优
4楼-- · 2018-12-31 23:44

How do I check if an element exists

if ($("#mydiv").length){  }

If it is 0, it will evaluate to false, anything more than that true.

There is no need for a greater than, less than comparison.

查看更多
看风景的人
5楼-- · 2018-12-31 23:53

Try this:

if ($("#mydiv").length > 0){
  // do something here
}

The length property will return zero if element does not exists.

查看更多
荒废的爱情
6楼-- · 2018-12-31 23:57

You can also use array-like notation and check for the first element. The first element of an empty array or collection is simply undefined, so you get the "normal" javascript truthy/falsy behaviour:

var el = $('body')[0];
if (el) {
    console.log('element found', el);
}
if (!el) {
    console.log('no element found');
}
查看更多
素衣白纱
7楼-- · 2018-12-31 23:59

your elemId as its name suggests, is an Id attribute, these are all you can do to check if it exists:

Vanilla JavaScript: in case you have more advanced selectors:

//you can use it for more advanced selectors
if(document.querySelectorAll("#elemId").length){}

if(document.querySelector("#elemId")){}

//you can use it if your selector has only an Id attribute
if(document.getElementById("elemId")){}

jQuery:

if(jQuery("#elemId").length){}
查看更多
登录 后发表回答