话不多说直接上demo:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <div class="container" id="box"><span>我是一个div元素1</span><p>hello</p></div> 9 <script> 10 var divNode = document.getElementsByClassName("container")[0]; 11 /*节点操作*/ 12 /*获取元素节点*/ 13 console.log(divNode.nodeType) //1 14 console.log(divNode.nodeName) //DIV 15 console.log(divNode.nodeValue) //null 16 17 /*获取属性节点*/ 18 console.log(divNode.attributes[1].nodeName) //id 19 console.log(divNode.attributes[0].nodeValue); //container 20 console.log(divNode.attributes[0]); //class="container" 21 22 /*获取文本节点*/ 23 console.log(divNode.childNodes[0].nodeName); //SPAN 24 console.log(divNode.childNodes[0].nodeValue); //null,如果不存在子元素,则输出文本内容 25 console.log(divNode.parentNode); //输出body标签及其子元素 26 console.log("===================") 27 console.log(divNode.childNodes[1].childNodes[0].nodeName); //#text 28 console.log(divNode.childNodes[1].childNodes[0].nodeValue); //hello /*如果div标签与span标签之间存在换行或者空格,则输出:我是一个div元素1*/ 29 /*元素方法操作*/ 30 /*添加子节点*/ 31 var addNode = document.createElement("div"); 32 var addText = document.createTextNode("guangzhou"); 33 addNode.appendChild(addText); 34 divNode.appendChild(addNode); 35 36 /*删除子节点*/ 37 var deleteNode = document.getElementsByTagName("span")[0] 38 divNode.removeChild(deleteNode); 39 40 /*替换子节点*/ 41 var replaceNode = divNode.getElementsByTagName("div")[0] 42 var newReplace = document.createElement("span"); 43 newReplace.innerHTML="my name lucas"; 44 divNode.replaceChild(newReplace,replaceNode); 45 46 /*插入子节点*/ 47 var newInsert = document.createElement("div"); 48 newInsert.innerHTML="insert a new div"; 49 divNode.insertBefore(newInsert,divNode.childNodes[0]); 50 51 /*属性操作*/ 52 /*获取属性节点*/ 53 console.log(divNode.getAttribute("class")); //container 54 console.log(divNode.getAttributeNode("class")); //class="container" 55 56 /*创建和设置属性节点*/ 57 var addAttr = document.createAttribute("class"); 58 addAttr.value="newAttr"; 59 divNode.setAttributeNode(addAttr); //替代了旧的类 60 // divNode.setAttribute("class","newAttr");/*简单写法*/ 61 62 /*删除属性*/ 63 var deleteAttr = divNode.getAttributeNode("class"); 64 divNode.removeAttributeNode(deleteAttr) 65 // divNode.removeAttribute("id") /*简单写法*/ 66 </script> 67 </body> 68 </html>
效果