最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - what is the difference between angular.element and document.getElementById - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question edited Nov 8, 2016 at 14:36 Günter Zöchbauer 659k234 gold badges2.1k silver badges1.6k bronze badges asked Nov 4, 2016 at 17:24 Mohammed AkdimMohammed Akdim 2,4011 gold badge15 silver badges21 bronze badges 2
  • thanks, but what's the best I can use in angular App and why ? – Mohammed Akdim Commented Nov 4, 2016 at 17:39
  • did my answer help? – Max Koretskyi Commented Nov 6, 2016 at 6:21
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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.


tl:dr;

Always read the documentation

发布评论

评论列表(0)

  1. 暂无评论