1.removeAttribute() 方法刪除指定的屬性。
注:removeAttributeNode() 方法從元素中刪除指定的屬性節(jié)點(diǎn)。
簡單的來講,removeAttribute() 移除元素內(nèi)的屬性;
菜鳥教程說:Internet Explorer不支持removeAttribute方法。但我測了一下發(fā)現(xiàn)在IE8及以上都沒問題
<style>
.aaa{
color:red;
}
</style>
</head>
<body>
<h1 class="aaa">Hello World</h1>
<button onclick="myFunction()">點(diǎn)擊</button>
<script>
function myFunction()
{
document.getElementsByTagName("h1")[0].removeAttribute("class"); //當(dāng)點(diǎn)擊的時(shí)候,h1的紅色會(huì)變成黑色(默認(rèn)黑色)應(yīng)為移除了class這個(gè)屬性
}
</script>
</body>
2.getAttribute() 方法通過名稱獲取屬性的值。(屬性不存在時(shí)返回null)
注:getAttributeNode() 方法從當(dāng)前元素中通過名稱獲取屬性節(jié)點(diǎn)。
<style>
.aaa{
color:red;
}
</style>
</head>
<body>
<h1 class="aaa">Hello World</h1>
<button onclick="myFunction()">點(diǎn)擊</button>
<script>
function myFunction()
{
var h1=document.getElementsByTagName("h1")[0];
alert(h1.className); //兩者都能有效果 aaa
alert(h1.getAttribute("class")); // aaa
}
</script>
</body>
獲取 dom 節(jié)點(diǎn)數(shù)據(jù)請(qǐng)不要用其他方法,統(tǒng)一用getattribute,獲取對(duì)象屬性方括號(hào)是兼容性最廣的,點(diǎn)號(hào)方便,但是低版本 ie 有兼容性問題。良好的編程習(xí)慣是減少bug的保證
3.setAttribute() 方法添加指定的屬性,并為其賦指定的值。
*注意:如果這個(gè)指定的屬性已存在,則僅設(shè)置/更改值。
和getAttribute一樣,setAttribute只是用于元素節(jié)點(diǎn)
<body>
<input value="OK">
<p>點(diǎn)擊按鈕來設(shè)置按鈕的 type 屬性。</p>
<button onclick="myFunction()">點(diǎn)擊</button>
<script>
function myFunction()
{
document.getElementsByTagName("input")[0].setAttribute("type","button");
}
</script>
</body>

點(diǎn)擊前.png

點(diǎn)擊后.png
Internet Explorer 8 以及更早的版本不支持此方法。
通過setAttribute對(duì)文檔做出修改后,在通過瀏覽器的源代碼查看時(shí)看到的仍然是改變前的屬性值。這種“表里不一”的現(xiàn)象源自DOM的工作模式:先加載文檔的靜態(tài)內(nèi)容,在動(dòng)態(tài)刷新,動(dòng)態(tài)刷新不影響文檔的靜態(tài)內(nèi)容。
-DOM編程藝術(shù)