dom元素attribute和property的区别


这篇文章主要介绍了javascript中attribute和property的区别详解,attribute和property对新手来讲,特别容易混淆概念,本文就清晰的讲解了它们的区别,须要的朋友能够参考下javascript

DOM元素的attribute和property很容易混倄在一块儿,分不清楚,二者是不一样的东西,可是二者又联系紧密。不少新手朋友,也包括之前的我,常常会搞不清楚。

attribute翻译成中文术语为“特性”,property翻译成中文术语为“属性”,从中文的字面意思来看,确实是有点区别了,先来讲说attribute。

attribute是一个特性节点,每一个DOM元素都有一个对应的attributes属性来存放全部的attribute节点,attributes是一个类数组的容器,说得准确点就是NameNodeMap,总之就是一个相似数组但又和数组不太同样的容器。attributes的每一个数字索引以名值对(name=”value”)的形式存放了一个attribute节点。
java

复制代码代码以下:数组

<div class="box" id="box" gameid="880">hello</div>浏览器


上面的div元素的HTML代码中有class、id还有自定义的gameid,这些特性都存放在attributes中,相似下面的形式:
spa

复制代码代码以下:翻译

[ class="box", id="box", gameid="880" ]对象


能够这样来访问attribute节点:
索引

复制代码代码以下:ip


var elem = document.getElementById( 'box' );
console.log( elem.attributes[0].name ); // class
console.log( elem.attributes[0].value ); // box
rem

可是IE6-7将不少东西都存放在attributes中,上面的访问方法和标准浏览器的返回结果又不一样。一般要获取一个attribute节点直接用getAttribute方法:

复制代码代码以下:

console.log( elem.getAttribute('gameid') ); // 880

要设置一个attribute节点使用setAttribute方法,要删除就用removeAttribute:

复制代码代码以下:

elem.setAttribute('testAttr', 'testVal');
console.log( elem.removeAttribute('gameid') ); // undefined

attributes是会随着添加或删除attribute节点动态更新的。
property就是一个属性,若是把DOM元素当作是一个普通的Object对象,那么property就是一个以名值对(name=”value”)的形式存放在Object中的属性。要添加和删除property也简单多了,和普通的对象没啥分别:

复制代码代码以下:


elem.gameid = 880; // 添加
console.log( elem.gameid ) // 获取
delete elem.gameid // 删除

之因此attribute和property容易混倄在一块儿的缘由是,不少attribute节点还有一个相对应的property属性,好比上面的div元素的id和class既是attribute,也有对应的property,无论使用哪一种方法均可以访问和修改。

复制代码代码以下:


console.log( elem.getAttribute('id') ); // box
console.log( elem.id ); // box
elem.id = 'hello';
console.log( elem.getAttribute('id') ); // hello

可是对于自定义的attribute节点,或者自定义property,二者就没有关系了。

复制代码代码以下:


console.log( elem.getAttribute('gameid') ); // 880
console.log( elem.gameid ); // undefined
elem.areaid = '900';
console.log( elem.getAttribute('areaid') ) // null

对于IE6-7来讲,没有区分attribute和property:

复制代码代码以下:


console.log( elem.getAttribute('gameid') ); // 880
console.log( elem.gameid ); // 880
elem.areaid = '900';
console.log( elem.getAttribute('areaid') ) // 900

不少新手朋友估计都很容易掉进这个坑中。
DOM元素一些默认常见的attribute节点都有与之对应的property属性,比较特殊的是一些值为Boolean类型的property,如一些表单元素:

复制代码代码以下:


<input type="radio" checked="checked" id="raido">
var radio = document.getElementById( 'radio' );
console.log( radio.getAttribute('checked') ); // checked
console.log( radio.checked ); // true

对于这些特殊的attribute节点,只有存在该节点,对应的property的值就为true,如:

复制代码代码以下:


<input type="radio" checked="anything" id="raido">
var radio = document.getElementById( 'radio' );
console.log( radio.getAttribute('checked') ); // anything
console.log( radio.checked ); // true

最后为了更好的区分attribute和property,基本能够总结为attribute节点都是在HTML代码中可见的,而property只是一个普通的名值对属性。

复制代码代码以下:

// gameid和id都是attribute节点// id同时又能够经过property来访问和修改<div gameid="880" id="box">hello</div> // areaid仅仅是propertyelem.areaid = 900;

相关文章