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ù)請不要用其他方法将谊,統(tǒng)一用getattribute,獲取對象屬性方括號(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對文檔做出修改后菇用,在通過瀏覽器的源代碼查看時(shí)看到的仍然是改變前的屬性值。這種“表里不一”的現(xiàn)象源自DOM的工作模式:先加載文檔的靜態(tài)內(nèi)容陷揪,在動(dòng)態(tài)刷新惋鸥,動(dòng)態(tài)刷新不影響文檔的靜態(tài)內(nèi)容。
-DOM編程藝術(shù)