Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 278
Dimitris Avatar asked Jun 20 '14 15:06

Dimitris


People also ask

How do you find if element with specific ID exists or not?

Approach 1: First, we will use document. getElementById() to get the ID and store the ID into a variable. Then compare the element (variable that store ID) with 'null' and identify whether the element exists or not.

How do you check if an array contains a value in AngularJS?

isArray() Function in AngularJS is used to return TRUE if the reference is an array and FALSE if it is not an array. Syntax: angular. isArray(value);

How do you check if ID is exist in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

How do I find the DOM element?

The easiest way to find an HTML element in the DOM, is by using the element id.


1 Answers

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.

like image 159
DrDyne Avatar answered Sep 29 '22 09:09

DrDyne