Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery $(this).attr("name") vs this.name

What is the main different between

$(this).attr("name")

and

this.name

and What is the technical explanation?

like image 768
Sameera Thilakasiri Avatar asked Apr 17 '14 10:04

Sameera Thilakasiri


People also ask

What is .attr in jQuery?

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.

How do I find the value of my ID?

You can simply use the jQuery attr() method to get or set the ID attribute value of an element.


2 Answers

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.

like image 75
Rory McCrossan Avatar answered Oct 14 '22 03:10

Rory McCrossan


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).

like image 21
Adrian Salazar Avatar answered Oct 14 '22 02:10

Adrian Salazar