Reputation: 2401
Angularjs
get element by id : You can use the angular.element(‘#element_id’);
to get the element by id where #element_id
is id of element.
Here is an alternative of javascript document.getElementById
in angularjs –
Angularjs get element by id:
var currentElement = angular.element('#element_id');
But what is the difference between angular.element and document.getElementById
Upvotes: 0
Views: 3825
Reputation: 105497
I would add to the @evolutionxbox answer, that document.getElementById
should probably be slightly faster than angular.element
, since it doensn't have to go through the routine of figuring out what is passed into the function and what steps should be taken based on that.
Regarding what should be used when. Since these two methods return different object types (jquery vs HTMLElement), you can select the method based on either the standard practice in your application - whether to use jquery elements or native dom elements for manipulation, or on what operations you're going to perform on them as some operations are easier to do with jquery object than with native HTMLElement.
For example, if you want to use any jquery method, like .hasClass()
you need to wrap element like this angular.element(document.getElementById('some')).hasClass()
, so it's easier to just go with angular.element('#some').hasClass();
in the first place.
Generally, I would go with angular.element
approach as it's preferred method inside angular's native directives.
Upvotes: 4
Reputation: 4122
When you select an object with an ID using angular.element (or jQuery), it takes a shortcut and uses document.getElementById
.
The biggest difference is that angular.element
is a jQuery alias, and returns a jQuery (or jQuery lite) object.
Whereas document.getElementById
is a native DOM method, which returns an HTMLElement object.
Always read the documentation
Upvotes: 4