<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> /* * cloneNode(boolean deep) * deep: false 仅克隆 当前的节点和属性 * true 克隆 完整的 节点 以及子节点和属性 * */ function cloneN(){ var p=document.getElementById("main"); var myDiv=p.cloneNode(true); p.appendChild(myDiv); myDiv.setAttribute("id","myDiv"); } </script> </head> <body onload="cloneN();"> <div id="main"> <span>节点1</span> <span>节点2</span> <span>节点3</span> <span>节点4</span> </div> </body> </html>
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>选择你喜欢的书</title> <style> *{font-size: 12px; font-family: "Arial", "微软雅黑"; line-height: 25px;} div{padding: 5px; text-align: center; } div span{display: block;} </style> </head> <body> <p>选择你喜欢的书:<input type="radio" name="book" onclick="book();">我和狗狗一起活下来 <input type="radio" name="book" onclick="book()">灰霾来了怎么办</p> <div><img src="" alt="" id="image" onclick="img();"><span></span></div> <script type="text/javascript"> function book(){ /*先获取单选框*/ var radios=document.getElementsByName("book"); /*获取img*/ var img= document.getElementById("image"); if(radios[0].checked){ /*给img标签中的属性 赋值*/ img.setAttribute("src","images/dog.jpg"); img.setAttribute("alt","这是一个小狗狗"); img.nextElementSibling.innerHTML="我和小狗狗一起活下去"; }else if(radios[1].checked){ /*给img标签中的属性 赋值*/ img.setAttribute("src","images/mai.jpg"); img.setAttribute("alt","雾霾来了。。。。。"); img.nextElementSibling.innerHTML="雾霾来了 活不下去...."; } } function img(){ alert(document.getElementById("image").getAttribute("src")); } </script> </body> </html>
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>节点之增删改</title> <script type="text/javascript"> window.onload=function(){ var ul= document.getElementsByTagName("ul")[0]; /*新增节点*/ var newLi= document.createElement("li"); newLi.innerHTML="小黑"; ul.appendChild(newLi); /*获取ul第三个li*/ var second= ul.getElementsByTagName("li")[2]; ul.insertBefore(newLi,second); /*clone*/ var ul2= document.getElementsByTagName("ul")[0].cloneNode(true); document.getElementById("d").appendChild(ul2); /*删除节点*/ var reNode= ul.getElementsByTagName("li")[0]; // ul.removeChild(reNode); /*替换节点*/ ul.replaceChild(newLi,reNode); } </script> </head> <body> <ul> <li>小强1</li> <li>小强2</li> <li>小强3</li> </ul> <div id="d"> </div> </body> </html>