一、创建DOM元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> window.onload = function() { var oBtn = document.getElementById(‘btn1‘); var oUl = document.getElementById(‘ul1‘); oBtn.onclick = function() { var oLi = document.createElement(‘li‘); //创建一个元素 oUl.appendChild(oLi); //把li插入到父级 } } </script> </head> <body> <input id="btn1" type="button" name="" value="创建li"> <ul id="ul1"></ul> </ul> </body> </html>
二、插入DOM元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> window.onload = function() { var oBtn = document.getElementById(‘btn1‘); var oUl = document.getElementById(‘ul1‘); var oTxt = document.getElementById(‘txt1‘); oBtn.onclick = function() { var oLi = document.createElement(‘li‘); //创建一个元素 var aLi = document.getElementsByTagName(‘li‘); oLi.innerHTML = oTxt.value; if (aLi.length == 0) { oUl.appendChild(oLi); //把li插入到父级后面 } else { oUl.insertBefore(oLi, aLi[0]); //把li插入到aLi[0]前面 } oTxt.value = ""; } } </script> </head> <body> <input id="txt1" type="text"> <input id="btn1" type="button" name="" value="插入"> <ul id="ul1"></ul> </ul> </body> </html>
三、删除DOM元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script> window.onload = function() { var aA = document.getElementsByTagName(‘a‘); var oUl = document.getElementById(‘ul1‘); var i = 0; for (i = 0; i < aA.length; i++) { aA[i].onclick = function() { oUl.removeChild(this.parentNode); //删除 } } } </script> </head> <body> <ul id="ul1"> <li>asdfasdf <a href="javascript:;">删除</a> </li> <li>123 <a href="javascript:;">删除</a> </li> <li>xcvx <a href="javascript:;">删除</a> </li> </ul> </body> </html>
时间: 2024-10-24 11:58:04