如果元素是通过.append()方法创建的,如何检查该元素是否存在?$('elemId').长度不适合我。
当前回答
您还可以使用类似数组的表示法并检查第一个元素。空数组或集合的第一个元素是未定义的,因此可以得到“正常”的javascript truthy/falsy行为:
var el = $('body')[0];
if (el) {
console.log('element found', el);
}
if (!el) {
console.log('no element found');
}
其他回答
$('elemId').length不适用于我
您需要将#放在元素id之前:
$('#elemId').length
---^
对于普通JavaScript,您不需要散列(#),例如document.getElementById('id_here'),但是在使用jQuery时,您确实需要像CSS一样基于id将散列放入目标元素。
尝试检查选择器的长度,如果它返回了一些内容,则元素必须存在,否则不存在。
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
}
如果元素上有类,则可以尝试以下操作:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
试试看:
if ($("#mydiv").length > 0){
// do something here
}
如果元素不存在,length属性将返回零。
你的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){}
推荐文章
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?
- 防止在ASP中缓存。NET MVC中使用属性的特定操作
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- jQuery: keyPress退格键不火?
- XMLHttpRequest Origin null不允许Access-Control-Allow-Origin for file:/// to file:///(无服务器)
- JavaScript: override alert()
- 重置setTimeout