如果元素是通过.append()方法创建的,如何检查该元素是否存在?$('elemId').长度不适合我。
$('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
}
你的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){}
您可以使用本机JS测试对象的存在:
if (document.getElementById('elemId') instanceof Object){
// do something here
}
别忘了,jQuery只不过是围绕本地Javascript命令和财产的复杂(而且非常有用)包装器
如何检查元素是否存在
if ($("#mydiv").length){ }
如果它为0,它的计算结果将为false,而不是true。
没有必要进行大于或小于比较。
您还可以使用类似数组的表示法并检查第一个元素。空数组或集合的第一个元素是未定义的,因此可以得到“正常”的javascript truthy/falsy行为:
var el = $('body')[0];
if (el) {
console.log('element found', el);
}
if (!el) {
console.log('no element found');
}
推荐文章
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何在另一个元素之后添加一个元素?
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA
- 如何将“camelCase”转换为“Camel Case”?
- 我们可以在另一个JS文件中调用用一个JavaScript编写的函数吗?