Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  65] [ 3]  / answers: 1 / hits: 34637  / 10 Years ago, fri, june 20, 2014, 12:00:00

How can I check if an element with a specific ID already exists in my DOM inside an Angular directive? 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.


What I am doing now as a workaround is using the .html() jqLite function like this:



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



console.log('only fires if element already exists');



}



Is there a better way to do this? I would like to avoid including the whole jQuery just for this.


More From » angularjs

 Answers
48

Both angular.element($document).find('#someElementID') and angular.element('#someElementID') return an empty array, in case several dom nodes matched the selector.



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.


[#70494] Wednesday, June 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
pranavrorys

Total Points: 466
Total Questions: 87
Total Answers: 115

Location: Barbados
Member since Sun, Nov 27, 2022
2 Years ago
pranavrorys questions
Fri, May 27, 22, 00:00, 2 Years ago
Thu, Oct 28, 21, 00:00, 3 Years ago
Sat, May 30, 20, 00:00, 4 Years ago
Fri, Dec 20, 19, 00:00, 5 Years ago
;