有两种方式可以修改DOM对象的属性:
[b]"."运算符 和 getAttribute(setAttribute)方法。[/b]
区别如下:
[b]对于style,className的设置,通常是使用.运算符来实现[/b]
HTMLElement由于继承自Element(继承自Node),因此拥有attributes对象,对属性的访问可以通过它来进行。attributes对象使用一个NamedNodeMap结构用于存放数据,NamedNodeMap本身也是一个'活'的对象,NamedNodeMap对象由Attr节点对象(nodeType = 2)构成。它有以下方法:
getNamedItem( name ) — 返回名称为name的Attr对象。
removeNamedItem( name ) — 删除名称为name的Attr对象。
setNamedItem( node ) — 添加一个Attr对象。
item( pos ) — 获取所以为pos的Attr对象。
通过attributes对象来读写属性还是比较少用的,不过,它在属性遍历方面倒是比较方便。具体看另一篇文章:http://mutongwu.iteye.com/admin/blogs/688017
[b]"."运算符 和 getAttribute(setAttribute)方法。[/b]
区别如下:
<div id='test' class="cls" dir="ltr" title="wott" ss="ss"></div>
var e = document.getElementById('test');
//获取属性
//用 . 来引用,必须是内置的(IE 可以访问自定义属性),而且引用的时候,区分大小写。
alert(e.id);//'test'
alert(e.className);//'cls'
alert(e.ss);//undefined(IE下为 'ss');
//用getAttribute 来引用,可以访问自定义属性,不区分大小写。
alert(e.getAttribute('id'));//'test'
alert(e.getAttribute('ID'));//'test'
//注意浏览器差异
alert(e.getAttribute('class'));//'cls'(Firefox)
alert(e.getAttribute('className'));//'cls'(IE)
alert(e.getAttribute('ss'));//'ss'
//设置属性
/*使用 . 运算符和 setAttribute都可以。但是对于自定义属性,使用.运算符的设置的属性无法通过getAttribute获取,反之亦然。*/
e.setAttribute('abc2','abc2');
e.abc3 = 'abc3';
e.title1 = 'abc';
alert(e.getAttribute('title1'));//null
[b]对于style,className的设置,通常是使用.运算符来实现[/b]
el.style.backgroundColor = 'blue';
el.className = 'nav';//works in all browers.
HTMLElement由于继承自Element(继承自Node),因此拥有attributes对象,对属性的访问可以通过它来进行。attributes对象使用一个NamedNodeMap结构用于存放数据,NamedNodeMap本身也是一个'活'的对象,NamedNodeMap对象由Attr节点对象(nodeType = 2)构成。它有以下方法:
getNamedItem( name ) — 返回名称为name的Attr对象。
removeNamedItem( name ) — 删除名称为name的Attr对象。
setNamedItem( node ) — 添加一个Attr对象。
item( pos ) — 获取所以为pos的Attr对象。
//例子:
<div id="xx"><p>xxxwww</p></div>
var attr = el.attributes;
alert(el.attributes.getNamedItem('id').nodeValue)//xx
//也可以通过[]号来访问
alert(el.attributes['id'].nodeValue)//xx
//修改ID对象值为xx2
attr['id'].nodeValue = 'xx2';
//删除ID对象
attr.removeNamedItem('id');
//获取第一个属性值
attr.item(0).nodeValue;
通过attributes对象来读写属性还是比较少用的,不过,它在属性遍历方面倒是比较方便。具体看另一篇文章:http://mutongwu.iteye.com/admin/blogs/688017