GetAttribute and setattribute can only be used for element nodes.
1. When an element node is obtained with getElementById
/*---------------------------index.html---------------------------*/
<! DOCTYPE html>
<meta name= "Author" content= "Hehe" >
<title>shopping list</title>
<body>
<p id= "purchases" title= "one" >what to buy</p>
<script type= "Text/javascript" src= "Script.js" ></script>
</body>
/*------------------------script.js---------------------------*/
var Paras=document.getelementbyid ("Purchases");
Alert (Paras.getattribute ("title"));
Paras.setattribute ("title", "ABCD");
Alert (Paras.getattribute ("title"));
At this point the warning box shows one, one shows ABCD.
2. When an element node is obtained with getElementsByTagName
/*---------------------index.html-----------------------------*/
<! DOCTYPE html>
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<meta name= "Author" content= "Hehe" >
<title>shopping list</title>
<body>
<p id= "purchases" title= "one" >what to buy</p>
<p title= "Both" >what to buy</p>
<script type= "Text/javascript" src= "Script.js" ></script>
</body>
/*----------------------------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"));
}
Now there are two warning boxes showing ABCD.
Note : getElementById Returns a node, and getElementsByTagName returns an array.
Double quotes are required for getattribute ("") and SetAttribute ("", "").
Alert () is not a display string without the need for double quotes.
GetAttribute and SetAttribute Usage