標籤:
一、擷取特定元素節點的屬性的值_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()