Dimitris Dimitris - 10 months ago 57
AngularJS Question

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? By using

an element is created if one does not exist, for example
will return an element whether one already exist or not.

What I am doing now as a workaround is using the
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.

Answer Source

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.