JavaScript的DOM_擷取/設定/移除特定元素節點的屬性_getAttribute()/setAttribute()/removeAttribute()

來源:互聯網
上載者:User

標籤:

一、擷取特定元素節點的屬性的值_getAttribute()

  1、getAttribute()方法將擷取元素中某個屬性的值。它和直接使用.屬性擷取屬性值的方法有一定區別。

<script type="text/javascript">    window.onload = function(){         var box = document.getElementById(‘box‘);            alert(box.bbb);                        // 擷取元素的自訂屬性值,非 IE 不支援   自訂的屬性不可以,結果是undefined            alert(box.getAttribute(‘bbb‘));        //擷取元素的自訂屬性值 這種方法可以相容自訂屬性            alert(box.getAttribute(‘class‘));    //getAttribute方法擷取標籤中的class屬性的值時在IE6,7中使用className,其他使用class需要做相容                        //跨瀏覽器擷取class屬性的值            if(box.getAttribute(‘className‘)==null){                alert(box.getAttribute(‘class‘));            }else{                box.getAttribute(‘className‘);            }    };</script></head><body><div id="box" class="pox" title="標題" style="color:#F00;" bbb="aaa">測試Div</div></body></html>

 

 

 

二、設定特定元素節點的屬性的值_setAttribute()

  1、setAttribute()方法將設定元素中某個屬性和值。它需要接受兩個參數:屬性名稱和值。如果屬性本身已存在,那麼就會被覆蓋。

<script type="text/javascript">     window.onload = function () {                                     var box = document.getElementById(‘box‘);            box.setAttribute(‘title‘,‘我是標題啊‘);            alert(box.title);       };</script></head><body>    <div id="box" class="pox" title="標題" style="color:#F00;" bbb="aaa">測試Div</div>    </body></html>

 

  2、使用該方法設定class和style屬性的時候在IE6,7中無效(所以不建議使用)

<script type="text/javascript">    window.onload = function(){         var box = document.getElementById(‘box‘);         box.setAttribute(‘style‘,‘color:green‘);//IE6,7無效         box.setAttribute(‘class‘,‘pox‘);//IE6,7無效              };</script></head><body><div id="box" title="標題" style="color:#F00;" bbb="aaa">測試Div</div></body>

 

 

 

 

三、removeAttribute()可以移除 HTML 元素中的屬性。 IE6不支援

<script type="text/javascript">     window.onload = function () {                                     var box = document.getElementById(‘box‘);            box.removeAttribute(‘title‘);            alert(box.title);    };</script></head><body>    <div id="box" class="pox" title="標題" style="color:#F00;" bbb="aaa">測試Div</div>    </body></html>

 

JavaScript的DOM_擷取/設定/移除特定元素節點的屬性_getAttribute()/setAttribute()/removeAttribute()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.