What is the main different between
$(this).attr("name")
and
this.name
and What is the technical explanation?
jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.
You can simply use the jQuery attr() method to get or set the ID attribute value of an element.
The first gets the attribute value from the jQuery object formed from the DOM element. The second gets the property directly from the DOM element, and is therefore quicker. You should use native properties where possible.
Well, I know you must be thinking... it's a performance matter... but no. It is a matter of reliability.
When you access the DOM through javascript, you don't have direct access to the DOM, what you get is an interface, defined by the HTML Specification of the W3C.
http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-798055546
The HTMLElement interface defines only this properties.
interface HTMLElement : Element {
attribute DOMString id;
attribute DOMString title;
attribute DOMString lang;
attribute DOMString dir;
attribute DOMString className;
};
So you will be able to call "this.name" only on those elements whose interface have a property "name" defined (most likely inputs).
This simple code will give you the idea of what can go wrong.
<a fakeAttr="Hola" id="myAnchor" data-mytext="Anyone?">Link</a>
$(function(){
/* This gives you undefined */
alert('Direct access: ' + $('#myAnchor')[0].fakeAttr);
/* This gets the work done */
alert('jQuery access: ' + $('#myAnchor').attr('fakeAttr'));
$('#myAnchor').click(function(){
/* This is of course empty */
alert(this.fakeAttr);
});
});
http://jsbin.com/ganihali/1/edit
How the browser builds the javascript-DOM proxy object may vary... IE used to be friendlier with developers and parse everything from the DOM and then give it to the developer as a ready to use object property. But that was prehistoric era, nowadays no browser will give you custom properties. Not even data-attributes (HTML5 valid).
So I would be very careful on making my light-fast error-prone access to properties and use a framework (there's a reason for that).
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