- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <head>
- <title>简单入门DOM</title>
- <script language="javascript">
- window.onload=initDom;
- function initDom(){
- document.getElementsByTagName("form")[0].onsubmit=function(){return initAdd();}
- document.getElementById("delNode").onclick=nodeDel;
- }
- function initAdd(){
- var txt=document.getElementById("textArea").value; //获取
- var newTxt = document.createTextNode(txt); //新建文本节点
- var newGref = document.createElement("p"); //新建元素节点
- newGref.appendChild(newTxt); //添加节点
- var docBody = document.getElementsByTagName("body")[0]; //取到文档尾
- docBody.appendChild(newGref); //添加节点
- return false; //不让表单提交
- }
- function nodeDel(){
- var t_node = document.getElementsByTagName("p");
- if(t_node.length > -1){
- if(t_node.length!=0){
- var node_id = t_node.item(t_node.length-1); //最后一个节点开始删除
- }else{
- alert("已经全部删除了");
- return false;
- }
- var docBody = document.getElementsByTagName("body")[0];
- docBody.removeChild(node_id); //执行删除节点操作
- return false;
- }
- }
- </script>
- <style type="text/css">
- body{ width: 600px; font-size: 12px; color: red; margin: 50px auto;}
- p{ padding: 10px; border: 1px solid #F90; background:#FDF1CC; }
- </style>
- </head>
- <body>
- <form action="#">
- <textarea id="textArea" rows="8" cols="80"></textarea><br /><br />
- <input type="submit" value="OK! 执行操作" />
- <br />
- <a href="#" id="delNode">删除节点!</a>
- </form>
- </body>
- </html>
简单的DOM,操纵节点
最新推荐文章于 2024-08-30 20:29:15 发布