The difference between prop () and attr () in jquery

Source: Internet
Author: User

Compared to the Attr,prop is 1.6.1 only new, both from the Chinese meaning understanding, are to get/set the property of the method (attributes and properties). Only the. attr () method used in window or document does not work properly before jQuery1.6 because the window and document cannot have attributes. Prop was born.

Since we want to know the difference between them, it's best to look at their source code, not to be frightened by the length of the code, we only look at the key words:

attrfunction(elem, name, value, pass) {varret, hooks, notxml, NType=Elem.nodetype;//don ' t get/set attributes on text, comment and attribute nodesif(!elem | | nType = = 3 | | nType = = 8 | | nType = = 2 ) { return; } if(Pass &&jquery.isfunction (jquery.fn[name])) { returnjQuery (elem) [name] (value);} //Fallback to prop when attributes is not supportedif(typeofElem.getattribute = = = "undefined" ) { returnJquery.prop (elem, name, value);} Notxml= NType!== 1 | | !Jquery.isxmldoc (elem);//All attributes is lowercase//Grab necessary Hook if one is definedif(notxml) {name=name.tolowercase (); Hooks= jquery.attrhooks[Name] | | (Rboolean.test (name)?Boolhook:nodehook); } if(Value!==undefined) { if(Value = = =NULL) {jquery.removeattr (elem, name);return; } Else if(Hooks && "Set"inchHooks && notxml && (ret = Hooks.set (elem, value, name))!==undefined) { returnret;} Else{elem.setattribute (name, value+ "" ); returnvalue;} } Else if(Hooks && "get"inchHooks && notxml && (ret = Hooks.get (elem, name))!==NULL ) { returnret;} Else{ret=Elem.getattribute (name);//non-existent attributes return null, we normalize to undefinedreturnret = = =NULL?Undefined:ret;} }prop Method Code (jquery version 1.8.3) Prop:function(elem, name, value) {varret, hooks, notxml, NType=Elem.nodetype;//don ' t get/set properties on text, comment and attribute nodesif(!elem | | nType = = 3 | | nType = = 8 | | nType = = 2 ) { return; } Notxml= NType!== 1 | | !Jquery.isxmldoc (elem);if(notxml) {//Fix name and attach hooksName = jquery.propfix[Name] | |name; hooks=jquery.prophooks[name];} if(Value!==undefined) { if(Hooks && "Set"inchHooks && (ret = Hooks.set (elem, value, name))!==undefined) { returnret;} Else { return(elem[name] =value); } } Else { if(Hooks && "get"inchHooks && (ret = Hooks.get (elem, name))!==NULL ) { returnret;} Else { returnelem[name];} } }

The attr method inside, the most critical of the two lines of code, Elem.setattribute (name, Value + "") and ret = Elem.getattribute (name), is clearly seen, using the DOM API The SetAttribute and GetAttribute methods manipulate the property element nodes. And the prop method inside, the most critical two lines of code, return (elem[name] = value) and return elem[name], you can understand so document.getElementById (EL) [Name] = value, which is a property that translates into a JS object.

Now that we understand the principle, let's take a look at an example:

<input type= "checkbox" id= "Test" abc= "111"/>

$ (function () {
El = $ ("#test");
Console.log (el.attr ("style")); Undefined
Console.log (El.prop ("style")); Cssstyledeclaration Object
Console.log (document.getElementById ("test"). Style); Cssstyledeclaration Object
});

El.attr ("style") output undefined, because attr is the value of the object property node obtained, it is clear that there is no such attribute node at this time, natural output undefinedel.prop ("style") The output Cssstyledeclaration object, which has a native style object property for a DOM object, outputs the style object as well as the document.getElementById ("test"). Style is the same as the one above.

Then look at:

EL.ATTR ("abc", "111")
Console.log (El.attr ("abc")); 111
Console.log (El.prop ("abc")); Undefined

First, add the ABC node attribute to this object using the Attr method, the value is 111, you can see the structure of the HTML has changed

EL.ATTR ("abc") output is 111, it is normal to El.prop ("abc") output undefined, because ABC is in this attribute node, so through prop is not access to

El.prop ("abc", "222");
Console.log (El.attr ("abc")); 111
Console.log (El.prop ("abc")); 222

We use the Prop method to set the ABC property to this object, the value is 222, you can see that the structure of HTML is unchanged. The result of the output is not explained.

The above has already made clear the principle, when with what can oneself grasp.

It is obviously better to use the Prop method when encountering properties such as checked,selected,readonly and disabled, such as the following:

<input type= "checkbox" id= "Test" checked= "Checked"/>console.log (el.attr ("checked")); Checked
Console.log (El.prop ("checked")); True
Console.log (el.attr ("Disabled")); Undefined
Console.log (El.prop ("Disabled")); False

Obviously, Boolean values make the next process more logical than string values.

PS, if you have JS performance neat, obviously prop performance is higher, because attr need to access the DOM attribute node, access to the DOM is the most time-consuming. This applies to multi-select and reverse selection scenarios.

We all know that some browsers just write disabled,checked can be, and some to write disabled = "disabled", checked= "checked", such as with attr ("checked") The Checked property of the checkbox can be obtained when the value is selected, the value is "checked", but the get value is undefined.

JQ provides a new method of "prop" to get these properties, which is to solve this problem, we used attr to get the checked property when we return "checked" and "", and now use the Prop method to get the property is unified return True and false.

So, when to use attr (), when to use Prop ()? 1. Add property name This property will take effect should use Prop (); 2. True,false Two attributes are used prop (); 3. Others use attr (); When you upgrade jquery in the project, you should pay attention to this!

Note: Works transferred from, http://jingyan.baidu.com/user/npublic?un=a5610988

The difference between prop () and attr () in jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.