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.
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.
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);
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.
The easiest way to find an HTML element in the DOM, is by using the element id.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With