JavaScript中的Attribute和Property区别

<div id="test" name="div1" class="center" customtag="divTest"/>html

上例中div里面的id、name、class还有自定义的customtag都放到了attributes里面,attributes相似数组的容器,名字索引存放的是name=value的attribute的节点数组


document.getElemmentById("test").getAttribute("customtag") //divTestspa


不少attribute节点有一个相应的property属性,如例子中的div元素的id和class既是attribute也有property,无论哪一种方式均可以访问和修改,可是对于自定义的attribute节点,或者自定义property,二者就没有关系了,对于IE6-7来讲,没有区分attribute和property。htm


虽然getAttribute和点号方法都能获取标准属性,可是他们对于某些属性,获取到的值存在差别性,好比href,src,value等索引

<a href="#" id="link">Test Link</a>ip

<img src="img.png" id="image" />get

<input type="text" value="enter text" id="ipt" />input

<script>io

var $ = function(id){return document.getElementById(id);};function

alert($('link').getAttribute('href'));//#

alert($('link').href);//fullpath/file.html#

alert($('image').getAttribute('src'))//img.png

alert($('image').src)//fullpath/img.png

alert($('ipt').getAttribute('value'))//enter text

alert($('ipt').value)//enter text

$('ipt').value = 5;

alert($('ipt').getAttribute('value'))//enter text

alert($('ipt').value)//5

相关文章
相关标签/搜索