检查jQuery中是否存在元素[重复]

本文翻译自:Check if element exists in jQuery [duplicate]

This question already has an answer here: 这个问题已经在这里有了答案:

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命令和属性的复杂(非常有用)包装器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值