JS操作DOM元素

來源:互聯網
上載者:User

標籤:

有兩種方式可以修改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元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.