The difference between attr and prop attributes in JS and preference Selection Example Introduction _ Basics

Source: Internet
Author: User

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

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

Attr:function (elem, name, value, pass) {var ret, hooks, notxml, ntype = Elem.nodetype; Don ' t get/set attributes on text, comment and attribute nodes if (!elem | | ntype = 3 | | ntype = 8 | | ntype = 2 
) {return; 
} if (pass && jquery.isfunction (jquery.fn[name)) {return jQuery (elem) [name] (value); }//fallback to prop when attributes are not supported if (typeof Elem.getattribute = = "undefined") {return jQuery 
. Prop (Elem, name, value); } notxml = ntype!== 1 | | 
!jquery.isxmldoc (Elem); 
All attributes are lowercase//Grab necessary hook if one is defined if (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" in hooks && notxml && (ret = Hooks.set (elem, value, name))!== Undefi 
Ned) {return ret; } ElSE {elem.setattribute (name, Value + ""); 
return value; 
' Else if ' (Hooks && ' get ' in hooks && notxml && (ret = Hooks.get (elem, name))!== null) { 
return ret; 
else {ret = Elem.getattribute (name); 
Non-existent attributes return NULL, "We normalize to undefined return ret = = null?" 
Undefined:ret; } 
}

Prop Method Code (jquery version 1.8.3)

Prop:function (elem, name, value) { 
var ret, hooks, notxml, 
ntype = Elem.nodetype; 
Don ' t get/set properties on text, comment and attribute nodes 
if (!elem | | ntype = 3 | | ntype = 8 | | ntype = = 2) {return 
; 
} 
Notxml = ntype!== 1 | | !jquery.isxmldoc (elem); 
if (notxml) { 
//Fix name and attach hooks 
name = jquery.propfix[Name] | | name; 
Hooks = jquery.prophooks[name]; 
if (value!== undefined) { 
if (hooks && "set" in hooks && (ret = Hooks.set (elem, value, name))!  = = undefined) {return 
ret; 
} else {return 
(elem[name] = value); 
} 
else { 
if (hooks && ' get ' in hooks && (ret = Hooks.get (elem, name))!== null) {return 
ret; 
} else { 
ret Urn elem[name];}} 

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

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

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

$ (function () { 
el = $ ("#test"); 
Console.log (el.attr ("style")); Undefined 
console.log (El.prop ("style"));//cssstyledeclaration Object 
Console.log ( "Test"). Style); Cssstyledeclaration object 
});

El.attr ("style") outputs the undefined, because attr is the value of the object's attribute node, and obviously there is no such attribute node at this time, the natural output undefined
El.prop ("style") outputs the Cssstyledeclaration object, which has a native style object property for a DOM object, so the style object is exported
As for document.getElementById ("test"). Style is the same as the one above.

Next look:

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


First, add the ABC node attribute to this object using the Attr method, with a value of 111, and you can see that the structure of the HTML is also changed

EL.ATTR ("abc") output is 111, which is normal.
El.prop ("abc") outputs undefined, because ABC is in this attribute node, so it cannot be fetched through prop

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

We then use the Prop method to set the ABC attribute to this object, with a value of 222, to see that the structure of the HTML is unchanged. The result of the output is not explained.

The above has already made the principle clear, when uses what to be possible oneself grasps.

To mention, it's obviously better to use the prop method when you encounter attributes such as checked,selected,readonly and disabled to get or set, 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")); 
Console.log (El.prop ("Disabled")); False


Obviously, a Boolean value is more reasonable than a string value to make the next processing.

PS, if you have JS performance neat, obviously prop performance is higher, because attr need to access the DOM property node, access to Dom is the most time-consuming. This applies to multiple-option selection and selection.

We all know that some browsers as long as the disabled,checked can be written, and some to write disabled = "disabled", checked= "checked", such as with attr ("checked") When the checkbox's Checked property is fetched, the value can be taken, the value is "checked", but the fetch value is not selected undefined.

JQ provides a new method "prop" to get these properties, which is to solve the problem, we used attr to get checked properties when we returned "checked" and "", and now we use the prop method to get the property then the uniform returns True and false.

So, when to use attr (), when to use Prop ()?
1. Add attribute name This property will take effect should use Prop ();
2. There are true,false two attributes using prop ();
3. Others use attr ();
You should pay attention to this when you upgrade jquery in your project!

The following is the use of the official recommendation attr (), prop ():

The following is the use of the official recommendation attr (), prop ():

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.