创建DOM元素
createElement(标签名) 创建一个节点
appendChild(节点) 追加一个节点---末尾
例子:为ul插入li
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function (){ var oBtn = document.getElementById('btn'); var oUl = document.getElementById('ul') var oTxt = document.getElementById('txt') oBtn.onclick = function () { //创建元素createElement(元素名) var oLi = document.createElement('li'); //将input里面的值赋给li oLi.innerHTML = oTxt.value; //父级.appendChild(子节点); oUl.appendChild(oLi); oTxt.value =''; }; } </script> </head> <body> <input type="text" name="" id="txt"> <input id="btn" type="button" value="创建"> </body> <ul id="ul"></ul> </html>
插入元素
insertBefore(节点,原有节点) 在已有元素前插入
例子:倒序插入ul
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function (){ var oBtn = document.getElementById('btn'); var oUl = document.getElementById('ul') var oTxt = document.getElementById('txt') oBtn.onclick = function () { //创建元素createElement(元素名) var oLi = document.createElement('li'); var aLi = document.getElementsByTagName('li') //将input里面的值赋给li oLi.innerHTML = oTxt.value; //父级.appendChild(子节点) if (aLi.length>0) { //在IE下 oUl.insertBefore(oLi,aLi[0]); }else{ oUl.appendChild(oLi); } oTxt.value =''; }; } </script> </head> <body> <input type="text" name="" id="txt"> <input id="btn" type="button" value="创建"> </body> <ul id="ul"></ul> </html>
删除DOM元素
removeChild(节点) 删除一个节点
例子:删除li
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function () { var oUl = document.getElementById('ul') var aA = document.getElementsByTagName("a") for(var i=0;i<aA.length;i++){ aA[i].onclick = function () { oUl.removeChild(this.parentNode) } } } </script> </head> <body> <ul id="ul"> <li>1<a href="javascript:;">删除</a></li> <li>1<a href="javascript:;">删除</a></li> <li>1<a href="javascript:;">删除</a></li> <li>1<a href="javascript:;">删除</a></li> <li>1<a href="javascript:;">删除</a></li> </ul> </body> </html>
文档碎片
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> window.onload = function (){ var oUl = document.getElementById('ul'); var oFrag = document.createDocumentFragment();//创建一个文档碎片 for( var i = 0;i<20;i++){ var oLi = document.createElement('li'); oFrag.appendChild(oLi); } oUl.appendChild(oFrag); } </script> </head> <body> <ul id="ul"> </ul> </body> </html>