標籤:
有兩種方式可以修改DOM對象的屬性:
"."運算子 和 getAttribute(setAttribute)方法。
區別如下:
Html代碼
1.[div id="test" class="cls" dir="ltr" title="wott" ss="ss"][/div]
[div id="test" class="cls" dir="ltr" title="wott" ss="ss"][/div]
Js代碼
1.var e = document.getElementById("test");
2.//擷取屬性
3.//用 . 來引用,必須是內建的(IE 可以訪問自訂屬性),而且引用的時候,區分大小寫。
4.alert(e.id);//"test"
5.alert(e.className);//"cls"
6.alert(e.ss);//undefined(IE下為 "ss");
7.
8.//用getAttribute 來引用,可以訪問自訂屬性,不區分大小寫。
9.alert(e.getAttribute("id"));//"test"
10.alert(e.getAttribute("ID"));//"test"
11.//注意瀏覽器差異
12.alert(e.getAttribute("class"));//"cls"(Firefox)
13.alert(e.getAttribute("className"));//"cls"(IE)
14.
15.alert(e.getAttribute("ss"));//"ss"
16.
17.//設定屬性
18./*使用 . 運算子和 setAttribute都可以。但是對於自訂屬性,使用.運算子的設定的屬性無法通過getAttribute擷取,反之亦然。*/
19.e.setAttribute("abc2","abc2");
20.e.abc3 = "abc3";
21.
22.e.title1 = "abc";
23.alert(e.getAttribute("title1"));//null
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
對於style,className的設定,通常是使用.運算子來實現
Js代碼
1.el.style.backgroundColor = "blue";
2.el.className = "nav";//works in all browers.
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對象。
JS操作DOM元素