简体   繁体   English

如何检查AngularJS中是否存在具有ID的元素

[英]How to check if element with ID exists in AngularJS

How can I check if an element with a specific ID already exists in my DOM inside an Angular directive? 如何检查Angular指令中的DOM中是否已存在具有特定ID的元素? By using angular.element() an element is created if one does not exist, for example angular.element('someID') will return an element whether one already exist or not. 通过使用angular.element() ,如果一个元素不存在,则创建一个元素,例如angular.element('someID')将返回一个元素,无论是否已经存在。

What I am doing now as a workaround is using the .html() jqLite function like this: 我现在正在做的解决方法是使用.html() jqLit​​e函数,如下所示:

if(angular.element('#someElementID'). html() ) { if(angular.element('#someElementID')。 html() ){

console.log('only fires if element already exists'); console.log('仅在元素已存在的情况下触发');

} }

Is there a better way to do this? 有一个更好的方法吗? I would like to avoid including the whole jQuery just for this. 我想避免为此包含整个jQuery。

Both angular.element($document).find('#someElementID') and angular.element('#someElementID') return an empty array, in case several dom nodes matched the selector. angular.element($ document).find('#someElementID')和angular.element('#someElementID')都返回一个空数组,以防多个dom节点与选择器匹配。

You should be pretty safe doing the following: 您应该非常安全地执行以下操作:

if ( angular.element('#someElementID').length ) {
    console.log('#someElementID exists');
}

Also keep in mind that jQLite .find() method only supports tag names. 还要记住,jQLite .find()方法仅支持标记名称。

I have tested, its working fine.. 我测试过,它工作正常..

If the ID is Exists, it return 1 如果ID为Exists,则返回1

ID is not Exists, it return 0 ID不存在,返回0

if(angular.element('#someElementID').length >0){
 console.log("Id is available.");
}else{
  console.log("Id is not available.");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM