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楼-- · 2019-01-01 00:01

Try to check the length of the selector, if it returns you something then the element must exists else not.

 if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}


 if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}
查看更多
栀子花@的思念
3楼-- · 2019-01-01 00:02

$('elemId').length doesn't work for me.

You need to put # before element id:

$('#elemId').length
---^

With vanilla JavaScript, you don't need the hash (#) e.g. document.getElementById('id_here') , however when using jQuery, you do need to put hash to target elements based on id just like CSS.

查看更多
登录 后发表回答