如果元素是通过.append()方法创建的,如何检查该元素是否存在?$('elemId').长度不适合我。
当前回答
如果元素上有类,则可以尝试以下操作:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
其他回答
如果元素上有类,则可以尝试以下操作:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
试试看:
if ($("#mydiv").length > 0){
// do something here
}
如果元素不存在,length属性将返回零。
如何检查元素是否存在
if ($("#mydiv").length){ }
如果它为0,它的计算结果将为false,而不是true。
没有必要进行大于或小于比较。
尝试检查选择器的长度,如果它返回了一些内容,则元素必须存在,否则不存在。
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
}
你的elemId正如它的名字所暗示的,是一个Id属性,你可以做这些来检查它是否存在:
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:
if(jQuery("#elemId").length){}