Difference between Property and Attribute: propertyattribute

Source: Internet
Author: User

Difference between Property and Attribute: propertyattribute

Property and attribute are very confusing. the Chinese translation of the two words is also very similar (property: attribute, attribute: feature). However, the two are actually different things and belong to different categories.

  • Property is a property in DOM and an object in JavaScript;
  • Attribute is a feature of HTML tags. Its value can only be a string;
Analyze property and attribute Based on JavaScript

The html contains the following code:

<input id="in_1" value="1" sth="whatever">

Simply create an input field on the html page (note that an attribute "something" does not exist in the DOM is added to this tag). Then, execute the following statement in JS:

var in1 = document.getElementById('in_1');

Execution statement

console.log(in1);     

From the printed results on the console, we can see that in1 contains an attribute named "attributes". Its type is NamedNodeMap, and there are also two basic attributes: "id" and "value, however, there is no custom attribute "something.

attributes: NamedNodeMapvalue: "1"id: "in_1"

Some consoles may not print properties on in1, so you can run the following command to print the properties to be observed:

console.log(in1.id);        // 'in_1'console.log(in1.value);     // 1console.log(in1.sth);       // undefined

It can be found that only "id" and "value" of the three attributes in the tag will be created on in1, and "something" will not be created. This is because every DOM object has its default basic attributes. When it is created, it only creates these basic attributes.DirectPut it in the DOM.

We perform an additional test, create another input tag, and perform similar operations:

Html:

<input id="in_2">

JS:

var in2 = document.getElementById('in_2');console.log(in2);

You can see from the printed information:

id: "in_2"value: null

Although "value" is not defined in the TAG, because it is the default basic attribute of DOM, it will still be created during DOM initialization. From this we can draw a conclusion:

  • DOM has its default basic attributes, which are called"Property"In any case, they will be created on the DOM object during initialization.
  • If you assign values to these attributes in the TAG, these values will be assigned to the DOM property with the same name as the initial value.

Now back to the first input ("# in_1"), we will ask, where did "something" go? Don't worry. Let's print out the attributes attribute.

console.log(in2);

There are several attributes:

0: id1: value2: sthlength: 3__proto__: NamedNodeMap

Originally, "something" was put into the attributes object, which records the number of attributes and attributes defined in the TAG in order. At this time, if you print out the attributes of the second input tag, you will find that there is only one "id" attribute, and "length" is 1.

It can be seen from this that attributes is a subset of property and stores the attributes defined on HTML tags. If we further explore every attribute in attitudes, we will find that they are not simple objects. They are Attr objects and have NodeType, NodeName, and other attributes. I will study this point later.Note:Printing attribute does not directly obtain the object value, but obtains a value that contains the attribute name and value.StringSuch:

console.log(in1.attibutes.sth);     // 'sth="whatever"'

We can conclude that:

  • Attributes and values defined in HTML tags Save the attributes of the DOM object;
  • The JavaScript type of these attribute attributes is Attr, not just the simplicity of saving the attribute name and value;

So what will happen if we change the value of property and attribute? Execute the following statement:

in1.value = 'new value of prop';console.log(in1.value);             // 'new value of prop'console.log(in1.attributes.value);  // 'value="1"'

At this time, the value in the input column on the page is changed to "new value of prop", and the value in propety is also changed to a new value, but attributes is still "1 ". It can be inferred from this that the values of attributes with the same name are not two-way bound.

If the value in attitudes is set in turn, what will happen?

in1.attributes.value.value = 'new value of attr';console.log(in1.value);             // 'new value of attr'console.log(in1.attributes.value);  // 'new value of attr'

In this case, the input column on the page is updated, and the value in property also changes. In addition, execute the following statement to get the same result.

in1.attributes.value.nodeValue = 'new value of attr';

Therefore, we can conclude that:

  • Property can be synchronized from attribute;
  • Attribute does not synchronize values on property.;
  • Data Binding between attribute and property is unidirectional. attribute-> property;
  • Changing any value on the property and attribute will reflect the update to the HTML page;
Analysis of attribute and property based on jQuery

So what are the attr and prop methods in jQuery?

First, use jQuery. prop to test

$(in1).prop('value', 'new prop form $');console.log(in1.value);             // 'new prop form $'console.log(in1.attributes.value);  // '1'

The value in the input column is updated, but the attribute is not updated.

Then use jQuery. attr to test

$(in1).attr('value', 'new attr form $');console.log(in1.value);             // 'new attr form $'console.log(in1.attributes.value);  // 'new attr form $'

The value in the input column is updated, and both property and attribute are updated.

From the above test, we can infer that jQuery. attr and jQuery. the effect of prop is basically the same as that of the native operation method. The property will get the synchronization from the attribute, but the attribute will not get the synchronization from the property. So how is jQuery implemented?

Next, let's take a look at the source code of jQuery. attr and jQuery. prop.

JQuery source code $ (). prop source code
JQuery. fn. extend ({prop: function (name, value) {return access (this, jQuery. prop, name, value, arguments. length> 1 );},... // removeProp method });
$ (). Attr source code
JQuery. fn. extend ({attr: function (name, value) {return access (this, jQuery. attr, name, value, arguments. length> 1 );},... // removeAttr method });

Both attr and prop call the access method to access the elements of the DOM object. To learn more, you must read the source code of access.

JQuery. access
// This is a multi-function that can be used to obtain or set the value of a set. // if this "value" is a function, the function will be executed. // @ param elems, element Set // @ param fn, method for processing the element // @ param key, element name // @ param value, new value // @ param chainable, whether to perform chained call // @ param emptyGet, // @ param raw, and whether the element is a non-function object var access = jQuery. access = function (elems, fn, key, value, chainable, emptyGet, raw) {var I = 0, // iteration count length = elems. length, // element length bulk = key = null; // determines whether a specific key (attribute name) exists. // For example If multiple attributes exist, recursively call them to access these values one by one if (jQuery. type (key) = "object") {chainable = true; for (I in key) {jQuery. access (elems, fn, I, key [I], true, emptyGet, raw);} // set a value} else if (value! = Undefined) {chainable = true; if (! JQuery. isFunction (value) {// if the value is not a function raw = true;} if (bulk) {// Bulk operations run against the entire set // if the attribute name is empty and the attribute name is not a function, use the external processing method fn and value to perform the operation if (raw) {fn. call (elems, value); fn = null ;//... when t when executing function values // If value is a function, then re-construct the processing method fn // This new fn will pass the value function as the callback function to the old processing method} else {bulk = fn; fn = function (elem, key, value ){ Return bulk. call (jQuery (elem), value) ;}}} if (fn) {// use the processing method fn to process each element in the element set for (; I <length; I ++) {fn (elems [I], key, raw? Value: value. call (elems [I], I, fn (elems [I], key); // if the value is a funciton, then, use this function to return a value and pass in fn }}return chainable? Elems: // if it is a chained call, the returned Element Set // Gets bulk? Fn. call (elems): length? Fn (elems [0], key): emptyGet ;};

Although the access method is not long, it is very difficult to understand it completely. Therefore, you can simplify access by calling jQuery. fn. attr.

Access Call in jQuery. fn. attr/jQuery. fn. prop

$ (). Attr call method:

  • $ (). Attr (propertyName) // obtain a single attribute
  • $ (). Attr (propertyName, value) // sets a single attribute
  • $ (). Attr (properties) // you can specify multiple attributes.
  • $ (). Attr (propertyName, function) // call the callback function for the attribute

The call method of prop is the same as that of attr. For the sake of simplicity, only the first and second call methods are studied here.

Call Statement:

access( this, jQuery.attr, name, value, arguments.length > 1 );

Simplified access:

// Elems current jQuery object, which may contain multiple DOM objects // fn jQuery. attr method // name attribute name // value of the value Attribute // chainable if the value is null, chainable is false; otherwise, chainable is truevar access = jQuery. access = function (elems, fn, key, value, chainable, emptyGet, raw) {var I = 0, // iteration count length = elems. length, // attribute quantity bulk = false; // key! = Null if (value! = Undefined) {// if the value is not empty, set a new value; otherwise, return the value chainable = true; raw = true; // value is not function if (fn) {// fn is jQuery. attr for (; I <length; I ++) {fn (elems [I], key, value); // jQuery. attr (elems, key, value) ;}} if (chainable) {// value is not empty, it indicates get return elems; // return element implementation chained call} else {if (length) {// if the length of the element set is not zero, return the attribute value of the first element return fn (elems [0], key); // jQuery. attr (elems [0], key) ;}else {return emptyGet; // return a default value, which is undefined }}};

By simplifying the code, we can know that access is used to traverse the element set obtained by the previous $ call and call the fn function for it. In jQuery. attr and jQuery. prop, access is used to traverse element sets and merge them to control attribute and property. The access source code contains multiple conditional transfer codes, which are dazzled. The ultimate goal is to implement the variables of element sets and perform different operations, complex Code simplifies jQuery interfaces and greatly improves code reusability. This means that the amount of code is reduced and the code density is increased, reducing the JS file size.

These are all off-questions. Now we return to the implementation of $ (). attr and $ (). prop. In general, both prototype methods use access to variable element sets and call jQuery. prop and jQuery. attr methods for each element. Note that jQuery. prop and jQuery. attr is not a method on the prototype chain, but a method of the jQuery object. It uses jQuery. extend (jQuery. fn. prop and jQuery. fn. attr uses jQuery. fn. extend ).

Let's take a look at the source code of these two methods.

JQury. attr
JQuery. extend ({attr: function (elem, name, value) {var hooks, ret, nType = elem. nodeType; // get Node type // If elem is empty or NodeType is of the following type // 2: Attr, attribute, subnode has Text, EntityReference // 3: Text, text Content in the element or attribute // 8: Comment, Comment // do not perform any operation if (! Elem | nType = 3 | nType = 8 | nType = 2) {return ;}// if the attitude method is supported, call the property method if (typeof elem. getAttribute === strundefined) {return jQuery. prop (elem, name, value);} // if the Node type of elem is not element (1) if (nType! = 1 |! JQuery. isXMLDoc (elem) {name = name. toLowerCase (); // For browser compatibility, obtain the hook function and process some special elements like hooks = jQuery. attrHooks [name] | (jQuery. expr. match. bool. test (name )? BoolHook: nodeHook);} if (value! = Undefined) {// if the value is not undefined, Run "SET" if (value = null) {// if the value is null, remove attribute jQuery. removeAttr (elem, name);} else if (hooks & "set" in hooks & (ret = hooks. set (elem, value, name ))! = Undefined) {return ret; // use the hook function} else {// use the setAttribute method of Dom elem. setAttribute (name, value + ""); // Note: convert value to string because all attribute values are string return values;} // if the value is undefined, run "GET"} else if (hooks & "get" in hooks & (ret = hooks. get (elem, name ))! = Null) {return ret; // use the hook function} else {ret = jQuery. find. attr (elem, name); // actually called Sizzle. attr. This method is used to solve compatibility issues to obtain the attribute value // return the obtained value return ret = null? Undefined: ret ;}},...});

The Code shows that jQuery. attr calls the getAttribute and setAttribute methods.

JQeury. prop
JQuery. extend ({... prop: function (elem, name, value) {var ret, hooks, notxml, nType = elem. nodeType; // filter comments, Attr, element text content if (! Elem | nType = 3 | nType = 8 | nType = 2) {return;} notxml = nType! = 1 |! JQuery. isXMLDoc (elem); if (notxml) {// if not the element name = jQuery. propFix [name] | name; // corrected the property name hooks = jQuery. propHooks [name]; // obtain the hook function} if (value! = Undefined) {// execute "SET" return hooks & "set" in hooks & (ret = hooks. set (elem, value, name ))! = Undefined? Ret: // call the hook function (elem [name] = value ); // assign a value directly to elem [name]} else {// execute "GET" return hooks & "get" in hooks & (ret = hooks. get (elem, name ))! = Null? Ret: // call the hook function elem [name]; // directly return elem [name] }},...});

JQuery. prop directly performs operations on the property on the DOM object.

By comparing jQuery. prop and jQuery. attr, we can find that the former performs operations on the property of the DOM object directly, while the latter calls the setAttribute and getAttribute methods. What are the setAttribute and getAttribute methods? What is the effect?

SetAttribute and getAttribute

Based on the input box used in the previous test, execute the following code:

In1.setAttribute ('value', 'new attr from setattribute'); console. log (in1.getAttribute ('value'); // 'new attr from setattribute' console. log (in1.value); // 'new attr from setattribute' console. log (in1.attributes. value); // 'value = "new attr from setAttribute" ', which is actually an Attr object

After the setAttribute is executed, the attributes with the same name in attributes are directly changed;
The getAttribute result is the same as the access property result, instead of returning an Attr object as the direct access to attritudes.

Special Example href

However, do all tags and attributes maintain this feature? Next, let's take a look at the href attribute/feature.

First, create a <a \> tag in html:

<a href='page_1.html' id='a_1'></a>

Execute the following code in the JS script:

console.log(a1.href);   // 'file:///D:/GitHub/JS/html/test_01/page_1.html'console.log(a1.getAttribute('href'));   // 'page_1.html'

We can see that the absolute path is saved in property, and the relative path is saved in attribute. So what happens if these values are changed?

Change attribute:

A1.setAttribute ('href ', 'page_2.html'); // relative path console. log (a1.href); // 'file: // D:/GitHub/JS/html/test_01/page_2.html 'console. log (a1.getAttribute ('href '); // 'page_2.html' a1. setAttribute ('href ','/page_3.html '); // the root directory path is console. log (a1.href); // 'file: // D:/page_3.html 'console. log (a1.getAttribute ('href '); //'/page_3.html'

Change property:

A1.href = 'home.html '; // relative path: console. log (a1.href); // 'file: // D:/GitHub/JS/html/test_01/home.html 'console. log (a1.getAttribute ('href '); // 'home.html' a1. href = '/home.html'; // the root directory path is console. log (a1.href); // 'file: // D:/home.html 'console. log (a1.getAttribute ('href '); //'/home.html'

From this point, we can find that href is a special property/feature, and the two are two-way binding. Changing either side will change the value of the other side. Furthermore, this is not a simple two-way binding. The href in property always saves the absolute path, while the href in attribute stores the relative path.

Here, the difference between attribute and property is a little more, but this makes people more confused. Are there other similar special examples?

Id

Try to change the id in property:

  a1.id = 'new_id';    console.log(a1.id);                     // 'new_id'    console.log(a1.getAttribute('id'));     // 'new_id'

Today, the id in attribute is synchronized from the id in property, and the data direction is changedProperty <=> attribute;

Disabled

Let's take a look at the disabled attribute. We will add the "disabled" feature to the first <input \>:

<Input id = "in_1" value = "1" Something = "whatever" disabled = 'Disabled '> // The input has been disabled.

Then execute the following code:

Console. log (in1.disabled); // truein1.setAttribute ('Disabled ', false); // set disabled in attribute. The console is not disabled whether it is false or null. log (in1); // trueconsole. log (in1.getAttribute ('Disabled '); // 'false'

Changing the disabled in attributes does not change the property or cancel the disabled Effect in the input column.
If you change it to the following code:

Console. log (in1.disabled); // truein1.disabled = false; // Disable console. log (in1.disabled); // falseconsole. log (in1.getAttribute ('Disabled '); // null, the disabled attribute has been removed

Or:

Console. log (in1.disabled); // truein1.removeAttribute ('Disabled '); // remove the disabled attribute to disable the console. log (in1.disabled); // falseconsole. log (in1.getAttribute ('Disabled '); // null, the disabled attribute has been removed

You can find that setting "disabled" in property to "false" will remove the "disabled" in attributes. In this way, the Data Binding becomes,Property <=> attribute;

Therefore, the data binding between property and attritude cannot simplyProperty <-attribute.

Summary

Having analyzed so much, I have a deeper understanding of the difference between property and attribute. Here we will summarize:

Create
  • The default basic property is created during DOM object initialization;
  • Only attributes defined in HTML tags are saved in the propertyAttributesAttribute;
  • Attribute will initialize the property with the same name, but the custom attribute will not appear in the property;
  • Attribute values areString;
Data Binding
  • The data of attributes is synchronized to the property, but the property change does not change the attribute;
  • For attributes/features such as value and class, the Data Binding direction is unidirectional,Attribute-> property;
  • ForIdData Binding is bidirectional,Attribute <=> property;
  • For disabled, if disabled on property is false, the disabled on attribute must exist. In this case, data binding can be consideredBidirectionalOf;
Use
  • You can use the setAttribute method of DOM to change the attribute at the same time;
  • If you directly access the value on attributes, you will get an Attr object. If you access the value through the getAttribute method, you will get the attribute value directly;
  • In most cases (unless there is a browser compatibility problem), jQuery. attr is implemented through setAttribute, while jQuery. prop directly accesses the property of the DOM object;

So far, it is concluded that property is an attribute of the DOM object itself, and attribute is a feature we assign to it by setting HTML tags, there are some special data connections between attributes/features with the same name of attribute and property, which are different for different attributes/features.

In fact, it is difficult to describe the differences and links between property and attribute here with simple technical features. I found the following answer on StackFlow, or it will be closer to the real answer:

These words existed way before Computer Science came around.

Attribute is a quality or object that we attribute to someone or something. For example, the scepter is an attribute of power and statehood.

Property is a quality that exists without any attribution. For example, clay has adhesive qualities; or, one of the properties of metals is electrical conductivity. Properties demonstrate themselves though physical phenomena without the need attribute them to someone or something. By the same token, saying that someone has masculine attributes is self-evident. In effect, you could say that a property is owned by someone or something.

To be fair though, in Computer Science these two words, at least for the most part, can be used interchangeably - but then again programmers usually don't hold degrees in English Literature and do not write or care much about grammar books :).

The two most critical statements are as follows:

  • Attribute is the trait or object that we assign to a thing.
  • Property is an existing property that does not need to be granted by the outside world.

PS: original

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.