刪除元素示例代碼
<html> <head> </head> <body> <div> <div id="delId"><h3>js刪除元素之div及其內容</h3><p>這是段落內容</p></div> </div> <button onclick="fun()">刪除div</button> <script> function fun(){ //刪除div var obj = document.getElementById("delId"); var parentObj = obj.parentNode;//獲取div的父對象 parentObj.removeChild(obj);//通過div的父對象把它刪除 } </script> </body> </html>
追加元素代碼示例
<html> <head> <title> new document </title> <meta name="generator" content="editplus"> <meta name="author" content=""> <meta name="keywords" content=""> <meta name="description" content=""> </head> <SCRIPT LANGUAGE="JavaScript"> window.onload = function (){ inp.onclick = function(){ var inp = document.getElementById("list").getElementsByTagName('li')[2]; //在第三個li后面插入一個li var div = document.createElement("li"); //創建一個li div.style.cssText = "width:100px;height:100px;border:1px solid red;"; //設置style //div.id = 'id1'; //賦值id inp.parentNode.insertBefore(div,inp.nextSibling) //傳入參數執行 } } </SCRIPT> <body> <input type="submit" id="inp" value="添加div" /> <ul id="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </body> </html>
插入子元素代碼示例
<html> <head> <title> new document </title> <meta name="generator" content="editplus"> <meta name="author" content=""> <meta name="keywords" content=""> <meta name="description" content=""> </head> <ul id="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> <body> <script language="javascript"> var o = document.getElementById('list').children[2]; //創建鏈接 function createA(url,text) { var a = document.createElement("a"); a.href = url; a.innerHTML = text; a.style.color = "red"; o.appendChild(a); } createA("http://www.***.com/","插入子元素"); </script> <script language="javascript"> var o = document.getElementById('list').children[1]; //創建DIV function createDIV(text) { var div = document.createElement("div"); div.innerHTML = text; o.appendChild(div); } createDIV("插入子元素"); </script> </body> </html>