利用js_API 执行对html文档元素的属性的CRUD操作
转自:http://my.oschina.net/felay/blog/303470
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>对html元素属性的增删改查操作</title> <style> #attr{text-align:center;font-size:24px;color:white;background:#008000;width:400px;height:30px; } .myclass{background:#828555;} </style> </head> <body> <div id="attr" class = "attrs" lang = "en" >对html元素属性的增删改查操作</div> <hr /> <button id="getAttr" onclick="getAttr()">访问DIV属性</button> <button id="updateAttr" onclick="updateAttr()">修改DIV属性</button> <button id="deleteAttr" onclick="deleteAttr()">删除DIV属性</button> <button id="addAttr" onclick="addAttr()">增加DIV属性</button> <script> //简化打印 function print(str){ document.write(str+"<br/>"); } //简化获取id function $(id){ return document.getElementById(id); } //遍历元素属性 function listNodeList(attrList){ for (var i = 0; i < attrList.length; i++) { print(attrList[i].nodeName+"--->"+attrList[i].nodeValue); } } //访问其属性 function getAttr(){ var divNode = $("attr"); var attrList = divNode.attributes; print("属性名称--->属性值"); listNodeList(attrList); } //修改属性,两种方式,推荐前一种 function updateAttr(){ var divNode = $("attr"); //第一种 divNode.setAttribute("class","myclass"); //推荐这种 //第二种 /* var attrList = divNode.attributes; for (var i = 0; i < attrList.length; i++) { if(attrList[i].nodeName == "class"){//如果属性值为class,我们就修改它 attrList[i].nodeValue = "myclass"; break; } } listNodeList(attrList);//如果查看修改的属性值,打开注释 */ } //删除指定属性 function deleteAttr(){ var divNode = $("attr"); divNode.removeAttribute("id"); } //增加新的属性 function addAttr(){ var divNode = $("attr"); var attrList = divNode.attributes; divNode.setAttribute("title","mytitle"); listNodeList(attrList); } </script> </body> </html>