Akash Kava
Akash Kava

Reputation: 39916

what is benefit of $(e).attr(name,value) vs e.setAttribute(name,value)?

Case: e is of type HtmlElement and not css selector

I am talking about any attribute, not just standard allowed ones, like atom-type or data-atom-type, whatever may be the name, will it work without jQuery?

I suspect $(e).attr(name,value) is too slow, first of all it is creating an entire jQuery object ($(e) !== $(e) // two objects are not same) (jsPerf: http://jsperf.com/jquery-attr-vs-native-setattribute/28) and then it invokes certain checks and then sets value, which most browsers easily support e.setAttribute.

Is there any problem replacing $(e).attr(name,value) to e.setAttribute(name,value)?

IE8 supports setAttribute as per MSDN documentation. Is there any mobile browser or any browser which will not support it?

Eventually I want to improve performance of my JavaScript framework, initially we used jQuery extensively for its cross browser DOM features.

We have now understood that unless you are using css selector, most functions such as attr,val,text are better called with their direct DOM counter part when you have instance of HtmlElement.

Upvotes: 2

Views: 605

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

I suspect $(e).attr(name,value) is too slow, first of all it is creating an entire jQuery object and then it invokes certain checks and then sets value, which most browsers easily support e.setAttribute.

If you measure it, you'll find that the difference in performance is large-ish in relative terms, but miniscule in absolute terms, and it's absolute terms we normally care about. It just doesn't matter in 99.999999% of cases. If you run into a specific performance problem, and trace it to using jQuery, then consider optimizing at that point.

what is benefit of $(e).attr(name,value) vs e.setAttribute(name,value)?

In the specific case you mention, where e is an HTMLElement, there are only a couple of benefits:

  • There are a couple of IE-specific bugs in setAttribute that jQuery works around for you

  • There are some "attributes" people set when they really should be setting a property, for instance checked or disabled; jQuery maps those (this is mostly a legacy feature these days, as people should be using prop)

  • It does some pre-processing on boolean values for you, letting you use $(e).attr("checked", true) when true really should be "checked"

IE8 supports setAttribute as per MSDN documentation. Is there any mobile browser or any browser which will not support it?

All browsers support setAttribute. As I mention earlier, various versions of IE have had various bugs in it, but it's there and mostly works.

Upvotes: 5

Related Questions