標籤:
getAttribute和setAttribute只能用於元素節點。
1.當用getElementById獲得元素節點時
/*---------------------------index.html---------------------------*/
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Author" content="Hehe">
<title>Shopping list</title>
</head>
<body>
<p id="purchases" title="one">What to buy</p>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
/*------------------------script.js---------------------------*/
var paras=document.getElementById("purchases");
alert(paras.getAttribute("title"));
paras.setAttribute("title","abcd");
alert(paras.getAttribute("title"));
此時警告框一個顯示one,一個顯示abcd。
2.當用getElementsByTagName獲得元素節點時
/*---------------------index.html-----------------------------*/
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="Author" content="Hehe">
<title>Shopping list</title>
</head>
<body>
<p id="purchases" title="one">What to buy</p>
<p title="two">What to buy</p>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
/*----------------------------script.js--------------------*/
var paras=document.getElementsByTagName("p");
for(var i=0;i<paras.length;i++){
paras[i].setAttribute("title","abcd");
alert(paras[i].getAttribute("title"));
}
此時有倆個警告框顯示abcd。
注:getElementById返回的是節點,getElementsByTagName返回的是數組。
getAttribute("")與setAttribute("","")都需要用到雙引號。
alert()不是顯示字串不需要用到雙引號。
getAttribute與setAttribute用法