Home  >  Article  >  Web Front-end  >  Detailed explanation of the difference between Property and Attribute in JavaScript

Detailed explanation of the difference between Property and Attribute in JavaScript

黄舟
黄舟Original
2017-03-11 15:23:401251browse

Property and attribute are very easy to confuse, and the Chinese translations of the two words are also very similar (property: attribute, attribute: characteristic), but in fact, they are different things and belong to different categories.

  • property is an attribute in the DOM and an object in JavaScript;

  • attribute is a property on the HTML tag, and its value can only be It is a string;

Based on JavaScript analysis of property and attribute

There is such a piece of code in html:

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

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

var in1 = document.getElementById(&#39;in_1&#39;);

Execute statement

console.log(in1);

Print from the console As a result, you can see that in1 contains an attribute named "attributes", its type is NamedNodeMap, and there are two basic attributes "id" and "value", but there is no custom attribute "sth".

attributes: NamedNodeMap
value: "1"
id: "in_1"

Some consoles may not print the attributes on in1, then you can execute the following command to print the attributes to be observed:

console.log(in1.id);		// &#39;in_1&#39;
console.log(in1.value);		// 1
console.log(in1.sth);		// undefined

It can be found that among the three attributes in the label, only "id" and "value" will be created on in1, while "sth" will not be created. This is because each DOM object will have its default basic attributes, and when it is created, it will only create these basic attributes. The attributes we customize in the TAG tag will not be placed directly. into the DOM. Let’s do an additional test, create another input tag, and do something like:

html:

<input id="in_2">

JS:

var in2 = document.getElementById(&#39;in_2&#39;);
console.log(in2);

From You can see in the print information:

id: "in_2"
value: null

Although we have not defined "value" in TAG, since it is the default basic attribute of DOM, it will still be created when DOM is initialized. From this we can conclude:

    DOM has its default basic properties, and these properties are the so-called
  • "property"

    , no matter what, they will be in It is created on the DOM object during initialization.

  • If these properties are assigned in TAG, then these values ​​will be assigned to the property of the same name in the DOM as the initial value.
  • Now returning to the first input ("#in_1"), we will ask, where did "sth" go? Don't worry, let's print out the attributes attribute and see.
console.log(in2);

There are several attributes on it:

0: id
1: value
2: sth
length: 3
__proto__: NamedNodeMap

It turns out that "sth" is placed in the attributes object, and this object is recorded in order. The attributes and the number of attributes we defined in the TAG. 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.

As you can see from here, attributes are a subset of property, which saves the attributes defined on HTML tags. If you further explore each attribute in attitudes, you will find that they are not simple objects. It is an Attr type object with NodeType, NodeName and other attributes. More on this later.

Note

, printing the attribute attribute will not directly obtain the value of the object, but obtain a string containing the attribute name and value , such as:

console.log(in1.attibutes.sth);		// &#39;sth="whatever"&#39;
From this you can get Out:

    The attributes and values ​​defined in the HTML tag will be saved in the attributes attribute of the DOM object;
  • The JavaScript of these attribute attributes The type is Attr, not just as simple as saving the attribute name and value;
  • So, what will be the effect if we change the values ​​of property and attribute? Execute the following statement:
in1.value = &#39;new value of prop&#39;;
console.log(in1.value);				// &#39;new value of prop&#39;
console.log(in1.attributes.value);	// &#39;value="1"&#39;

At this time, the value of the input field on the page becomes "new value of prop", and the value in property also becomes the new value, but attributes are still " 1". It can be inferred from here that the values ​​​​of properties with the same name of property and attribute are not two-way bound.

What would be the effect if we set the value in attitudes instead?

in1.attributes.value.value = &#39;new value of attr&#39;;
console.log(in1.value);				// &#39;new value of attr&#39;
console.log(in1.attributes.value);	// &#39;new value of attr&#39;

At this time, the input field in the page is updated, and the value in the property also changes. In addition, executing the following statement will get the same result

in1.attributes.value.nodeValue = &#39;new value of attr&#39;;

From this, we can draw the conclusion:

  • property can be synchronized from attribute

  • Attribute will not synchronize the value on property

  • Data binding between attribute and property It is one-way, attribute->property;
  • Change any value on property and attribute, the update will be reflected in the HTML page;
  • Analyzing attributes and properties based on jQuery

So what are the attr and prop methods in jQuery?

First use jQuery.prop to test

$(in1).prop(&#39;value&#39;, &#39;new prop form $&#39;);

console.log(in1.value);				// &#39;new prop form $&#39;
console.log(in1.attributes.value);	// &#39;1&#39;

The value of the input field is updated, but the attribute is not updated.

Then use jQuery.attr to test

$(in1).attr(&#39;value&#39;, &#39;new attr form $&#39;);

console.log(in1.value);				// &#39;new attr form $&#39;
console.log(in1.attributes.value);	// &#39;new attr form $&#39;

The value of the input field is updated, and both the property and attribute are updated.

It can be inferred from the above test phenomenon that jQuery.attr and jQuery.prop are basically the same as the native operation methods. The property will get synchronization from the attribute, but the attribute will not get synchronization from the property. So how does jQuery implement it?

下面,我们来看看jQuery.attr和jQuery.prop的源码。

jQuery源码

$().prop源码

jQuery.fn.extend({
	prop: function( name, value ) {
		return access( this, jQuery.prop, name, value, arguments.length > 1 );
	},
	... // removeProp方法
});

$().attr源码

jQuery.fn.extend({
	attr: function( name, value ) {
		return access( this, jQuery.attr, name, value, arguments.length > 1 );
	},
	... // removeAttr方法
});

无论是attr还是prop,都会调用access方法来对DOM对象的元素进行访问,因此要研究出更多内容,就必须去阅读access的实现源码。

jQuery.access

// 这是一个多功能的函数,能够用来获取或设置一个集合的值
// 如果这个“值”是一个函数,那么这个函数会被执行

// @param elems, 元素集合
// @param fn, 对元素进行处理的方法
// @param key, 元素名
// @param value, 新的值
// @param chainable, 是否进行链式调用
// @param emptyGet,
// @param raw, 元素是否一个非function对象
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
	var i = 0,						// 迭代计数
		length = elems.length,		// 元素长度
		bulk = key == null;			// 判断是否有特定的键(属性名)

	// 如果存在多个属性,递归调用来逐个访问这些值
	if ( jQuery.type( key ) === "object" ) {
		chainable = true;
		for ( i in key ) {
			jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
		}

	// 设置一个值
	} else if ( value !== undefined ) {
		chainable = true;

		if ( !jQuery.isFunction( value ) ) {	// 如果值不是一个function
			raw = true;
		}

		if ( bulk ) {
			// Bulk operations run against the entire set
			// 如果属性名为空且属性名不是一个function,则利用外部处理方法fn和value来执行操作
			if ( raw ) {
				fn.call( elems, value );
				fn = null;

			// ...except when executing function values
			// 如果value是一个function,那么就重新构造处理方法fn
			// 这个新的fn会将value function作为回调函数传递给到老的处理方法
			} else {
				bulk = fn;
				fn = function( elem, key, value ) {
					return bulk.call( jQuery( elem ), value );
				};
			}
		}

		if ( fn ) {	// 利用处理方法fn对元素集合中每个元素进行处理
			for ( ; i < length; i++ ) {
				fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
				// 如果value是一个funciton,那么首先利用这个函数返回一个值并传入fn
			}
		}
	}

	return chainable ?
		elems :			// 如果是链式调用,就返回元素集合

		// Gets
		bulk ?
			fn.call( elems ) :
			length ? fn( elems[0], key ) : emptyGet;
};

access方法虽然不长,但是非常绕,要完全读懂并不简单,因此可以针对jQuery.fn.attr的调用来简化access。

jQuery.fn.attr/ jQuery.fn.prop 中的access调用

$().attr的调用方式:

  • $().attr( propertyName ) // 获取单个属性

  • $().attr( propertyName, value ) // 设置单个属性

  • $().attr( properties ) // 设置多个属性

  • $().attr( propertyName, function ) // 对属性调用回调函数

prop的调用方式与attr是一样的,在此就不重复列举。为了简单起见,在这里只对第一和第二种调用方式进行研究。

调用语句:

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

简化的access:

// elems 当前的jQuery对象,可能包含多个DOM对象
// fn jQuery.attr方法
// name 属性名
// value 属性的值
// chainable 如果value为空,则chainable为false,否则chainable为true

var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {

	var i = 0,						// 迭代计数
		length = elems.length,		// 属性数量
		bulk = false;				// key != null

	if ( value !== undefined ) {	// 如果value不为空,则为设置新值,否则返回该属性的值
		chainable = true;
		raw = true;				// value不是function

		if ( fn ) {	// fn为jQuery.attr
			for ( ; i < length; i++ ) {
				fn( elems[i], key, value);		// jQuery.attr(elems, key, value);
			}
		}
	}

	if(chainable) {			// value不为空,表示是get
		return elems;		// 返回元素实现链式调用
	} else {
		if(length) {		// 如果元素集合长度不为零,则返回第一个元素的属性值
			return fn(elems[0], key); 	// jQuery.attr(elems[0], key);
		} else {
			return emptyGet;		// 返回一个默认值,在这里是undefined
		}
	}
};

通过简化代码,可以知道,access的作用就是遍历上一个$调用得到的元素集合,对其调用fn函数。在jQuery.attr和jQuery.prop里面,就是利用access来遍历元素集合并对其实现对attribute和property的控制。access的源码里面有多段条件转移代码,看起来眼花缭乱,其最终目的就是能够实现对元素集合的变量并完成不同的操作,复杂的代码让jQuery的接口变得更加简单,能极大提高代码重用性,意味着减少了代码量,提高代码的密度从而使JS文件大小得到减少。

这些都是题外话了,现在回到$().attr和$().prop的实现。总的说,这两个原型方法都利用access对元素集进行变量,并对每个元素调用jQuery.prop和jQuery.attr方法。要注意,这里的jQuery.prop和jQuery.attr并不是原型链上的方法,而是jQuery这个对象本身的方法,它是使用jQuery.extend进行方法扩展的(jQuery.fn.prop和jQuery.fn.attr是使用jQuery.fn.extend进行方法扩展的)。

下面看看这两个方法的源码。

jQury.attr

jQuery.extend({
	attr: function( elem, name, value ) {
		var hooks, ret,
			nType = elem.nodeType;	// 获取Node类型

		// 如果 elem是空或者NodeType是以下类型
		// 		2: Attr, 属性, 子节点有Text, EntityReference
		// 		3: Text, 元素或属性中的文本内容
		// 		8: Comment, 注释
		// 不执行任何操作
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		// 如果支持attitude方法, 则调用property方法
		if ( typeof elem.getAttribute === strundefined ) {
			return jQuery.prop( elem, name, value );
		}

		// 如果elem的Node类型不是元素(1)
		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
			name = name.toLowerCase();
			// 针对浏览器的兼容性,获取钩子函数,处理一些特殊的元素
			hooks = jQuery.attrHooks[ name ] ||
				( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
		}

		if ( value !== undefined ) {		// 如果value不为undefined,执行"SET"

			if ( value === null ) {			// 如果value为null,则移除attribute
				jQuery.removeAttr( elem, name );	

			} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
				return ret;					// 使用钩子函数

			} else {						// 使用Dom的setAttribute方法
				elem.setAttribute( name, value + "" );		// 注意,要将value转换为string,因为所有attribute的值都是string
				return value;
			}

		// 如果value为undefined,就执行"GET"
		} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
			return ret;			// 使用钩子函数

		} else {
			ret = jQuery.find.attr( elem, name );	// 实际上调用了Sizzle.attr,这个方法中针对兼容性问题作出处理来获取attribute的值

			// 返回获得的值
			return ret == null ?
				undefined :
				ret;
		}
	},

	...
});

从代码可以发现,jQuery.attr调用的是getAttribute和setAttribute方法。

jQeury.prop

jQuery.extend({

	...	
	prop: function( elem, name, value ) {
		var ret, hooks, notxml,
			nType = elem.nodeType;

		// 过滤注释、Attr、元素文本内容
		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
			return;
		}

		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );

		if ( notxml ) {		// 如果不是元素
			name = jQuery.propFix[ name ] || name;	// 修正属性名
			hooks = jQuery.propHooks[ name ];		// 获取钩子函数
		}

		if ( value !== undefined ) {		// 执行"SET"
			return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
				ret :						// 调用钩子函数
				( elem[ name ] = value );	// 直接对elem[name]赋值

		} else {							// 执行"GET"
			return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
				ret :				// 调用钩子函数
				elem[ name ];		// 直接返回elem[name]
		}
	},

	...
});

jQuery.prop则是直接对DOM对象上的property进行操作。

通过对比jQuery.prop和jQuery.attr可以发现,前者直接对DOM对象的property进行操作,而后者会调用setAttribute和getAttribute方法。setAttribute和getAttribute方法又是什么方法呢?有什么效果?

setAttribute和getAttribute

基于之前测试使用的输入框,执行如下代码:

in1.setAttribute(&#39;value&#39;, &#39;new attr from setAttribute&#39;);

console.log(in1.getAttribute(&#39;value&#39;));			// &#39;new attr from setAttribute&#39;
console.log(in1.value);							// &#39;new attr from setAttribute&#39;
console.log(in1.attributes.value);				// &#39;value="new attr from setAttribute"&#39;,实际是一个Attr对象

执行完setAttribute以后,就如同直接更改attributes中的同名属性;
而getAttribute的结果与访问property的结果一模一样,而不会像直接访问attritudes那样返回一个Attr对象。

特殊的例子

href

然而,是不是所有标签,所有属性都维持保持这样的特性呢?下面我们看看href这个属性/特性。

首先在html中创建一个标签:

<a href=&#39;page_1.html&#39; id=&#39;a_1&#39;></a>

在JS脚本中执行如下代码:

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

可以看到,property中保存的是绝对路径,而attribute中保存的是相对路径。那么,如果更改了这些值会发生什么情况呢?

更改attribute:

a1.setAttribute(&#39;href&#39;, &#39;page_2.html&#39;);		// 相对路径
console.log(a1.href);	// &#39;file:///D:/GitHub/JS/html/test_01/page_2.html&#39;
console.log(a1.getAttribute(&#39;href&#39;));	// &#39;page_2.html&#39;

a1.setAttribute(&#39;href&#39;, &#39;/page_3.html&#39;);	// 根目录路径
console.log(a1.href);						// &#39;file:///D:/page_3.html&#39;
console.log(a1.getAttribute(&#39;href&#39;));		// &#39;/page_3.html&#39;

更改property:

a1.href = &#39;home.html&#39;;	// 相对路径
console.log(a1.href);	// &#39;file:///D:/GitHub/JS/html/test_01/home.html&#39;
console.log(a1.getAttribute(&#39;href&#39;));	// &#39;home.html&#39;

a1.href = &#39;/home.html&#39;;	// 根目录路径
console.log(a1.href);	// &#39;file:///D:/home.html&#39;
console.log(a1.getAttribute(&#39;href&#39;));	// &#39;/home.html&#39;

从这里可以发现,href是特殊的属性/特性,二者是双向绑定的,更改任意一方,都会导致另一方的的值发生改变。而且,这并不是简单的双向绑定,property中的href永远保存绝对路径,而attribute中的href则是保存相对路径。

看到这里,attribute和property的区别又多了一点,然而,这又让人变得更加疑惑了。是否还有其他类似的特殊例子呢?

id

尝试改变property中的id:

	a1.id = &#39;new_id&#39;;
	console.log(a1.id);						// &#39;new_id&#39;
	console.log(a1.getAttribute(&#39;id&#39;));		// &#39;new_id&#39;

天呀,现在attribute中的id从property中的id发生了同步,数据方向变成了property attribute

disabled

再来看看disabled这个属性,我们往第一个添加“disabled”特性:

<input id="in_1" value="1" sth="whatever" disabled=&#39;disabled&#39;>	// 此时input已经被禁用了

然后执行下面的代码:

console.log(in1.disabled);		// true
in1.setAttribute(&#39;disabled&#39;, false);	// 设置attribute中的disabled,无论是false还是null都不会取消禁用
console.log(in1);				// true
console.log(in1.getAttribute(&#39;disabled&#39;));	// &#39;false&#39;

改变attributes中的disabled不会改变更改property,也不会取消输入栏的禁用效果。

如果改成下面的代码:

console.log(in1.disabled);		// true
in1.disabled = false;			// 取消禁用
console.log(in1.disabled);		// false
console.log(in1.getAttribute(&#39;disabled&#39;));	// null,attribute中的disabled已经被移除了

又或者:

console.log(in1.disabled);		// true
in1.removeAttribute(&#39;disabled&#39;);	// 移除attribute上的disabled来取消禁用
console.log(in1.disabled);		// false
console.log(in1.getAttribute(&#39;disabled&#39;));	// null,attribute中的disabled已经被移除了

可以发现,将property中的disabled设置为false,会移除attributes中的disabled。这样数据绑定又变成了,propertyattribute;

所以property和attritude之间的数据绑定问题并不能单纯地以“property”来说明。

总结

分析了这么多,对property和attribute的区别理解也更深了,在这里总结一下:

Creation

  • The default basic property will be created when the DOM object is initialized;

  • Only attributes defined in HTML tags will be created Is saved in the attributes attribute of the property;

  • attribute will initialize the attribute with the same name in the property, but the customized attribute will not appear in the property;

  • The values ​​of attribute are all strings;

Data binding

  • The data of attributes will be synchronized to the property, but changes to the property will not change the attribute;

  • For attributes/features such as value and class, the direction of data binding is one-way ,attribute->property;

  • For id, data binding is two-way,attribute;

  • For disabled, when disabled on the property is false, disabled on the attribute will definitely exist. At this time, data binding can be considered as Bidirectional;

Using

  • You can use the setAttribute method of DOM to change the attribute at the same time;

  • Directly accessing the value on attributes will get an Attr object, while accessing through the getAttribute method will directly get the attribute value;

  • In most cases (unless there is a browser Compatibility issues), jQuery.attr is implemented through setAttribute, and jQuery.prop will directly access the property of the DOM object;

So far, it can be concluded that the property is the DOM object itself It has attributes, and attributes are attributes we give it by setting HTML tags. There will be some special data connections between attributes and properties of the same name, and these connections will be different for different attributes/features. difference.

In fact, here, the difference and connection between property and attribute are difficult to describe with simple technical characteristics. I found the following answer on StackFlow, which may 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 Detailed explanation of the difference between Property and Attribute in JavaScript .

The two most critical sentences:

  • Attribute (characteristic) is the quality or object we attribute to something.

  • Property (property) is a characteristic that already exists and does not need to be given by the outside world.

The above is the detailed content of Detailed explanation of the difference between Property and Attribute in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn