本文翻译自:Check if element exists in jQuery [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
- Is there an “exists” function for jQuery? jQuery是否有“存在”功能? 41 answers 41个答案
How do I check if an element exists if the element is created by .append() method? 如果该元素是由.append()方法创建的,该如何检查该元素是否存在? $('elemId').length doesn't work for me. $('elemId').length对我不起作用。
#1楼
参考:https://stackoom.com/question/JGiT/检查jQuery中是否存在元素-重复
#2楼
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楼
If you have a class on your element, then you can try the following: 如果您的元素上有一个类,则可以尝试以下操作:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
#4楼
Try this: 尝试这个:
if ($("#mydiv").length > 0){
// do something here
}
The length property will return zero if element does not exists. 如果元素不存在,则length属性将返回零。
#5楼
your elemId as its name suggests, is an Id attribute, these are all you can do to check if it exists: 顾名思义,您的elemId是一个Id属性,您可以检查它们是否存在:
Vanilla JavaScript: in case you have more advanced selectors: Vanilla JavaScript:如果您有更多高级选择器:
//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: jQuery的:
if(jQuery("#elemId").length){}
#6楼
You can use native JS to test for the existence of an object: 您可以使用本机JS来测试对象的存在:
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 别忘了,jQuery只是围绕本机Javascript命令和属性的复杂(非常有用)包装器

3422

被折叠的 条评论
为什么被折叠?



