createElement(标签名) 创建一个节点
appendChild(节点) 追加一个节点 (添加到末尾)
//父级.appendChild(子节点)
例子:为ul插入li
<html>
<head>
<meta charset="utf-8" />
<title>title>
head>
<script>
window.onload = function()
{
var oUl = document.getElementById("ul1");
var oBtn = document.getElementById("btn1");
var oTxt = document.getElementById("txt1");
oBtn.onclick = function()
{
var oLi = document.createElement("li");
oLi.innerHTML = oTxt.value;
//父级.appendChild(子节点)
oUl.appendChild(oLi);
};
};
script>
<body>
<input id="txt1" type="text" />
<input id="btn1" type="button" value="创建li"/>
<ul id="ul1">
ul>
body>
html>
insertBefore(节点, 原有节点) 在已有元素前插入
//父级.insertBefore(子节点,在谁之前)
例子:倒序插入li
<html>
<head>
<meta charset="utf-8" />
<title>title>
head>
<script>
window.onload = function()
{
var oUl = document.getElementById("ul1");
var oBtn = document.getElementById("btn1");
var oTxt = document.getElementById("txt1");
oBtn.onclick = function()
{
var oLi = document.createElement("li");
var aLi = oUl.getElementsByTagName("li"); //获取当前已有的li
oLi.innerHTML = oTxt.value;
//父级.appendChild(子节点)
//oUl.appendChild(oLi);
if(aLi.length > 0)
{
oUl.insertBefore(oLi, aLi[0]);
}
else
{
oUl.appendChild(oLi);
}
};
};
script>
<body>
<input id="txt1" type="text" />
<input id="btn1" type="button" value="创建li"/>
<ul id="ul1">
ul>
body>
html>
removeChild(节点) 删除一个节点
例子:删除li
<html>
<head>
<meta charset="utf-8" />
<title>title>
head>
<script>
window.onload = function()
{
var oUl = document.getElementById("ul1");
var aA = document.getElementsByTagName("a");
for(var i=0; ifunction()
{
oUl.removeChild(this.parentNode);
};
}
};
script>
<body>
<ul id="ul1">
<li>12345<a href="javascript:;">删除a>li>
<li>deibgnedsadvgg<a href="javascript:;">删除a>li>
<li>bbbbbbbbb<a href="javascript:;">删除a>li>
<li>aaaaa<a href="javascript:;">删除a>li>
<li>pdkgeog<a href="javascript:;">删除a>li>
ul>
body>
html>
文档碎片可以提高DOM操作性能(理论上)
文档碎片原理: 如果每添加一个元素就直接加到文档里,那么每一次添加都要重新渲染一次,效率很低。 因此,我们可以将添加的元素加到文档碎片里,再一次性地加入文档里。
文档碎片在低级浏览器中提高性能比较明显,但在高级浏览器中不一定,还可能降低性能。
document.createDocumentFragment()
例子: 不用文档碎片
<html>
<head>
<meta charset="utf-8" />
<title>title>
head>
<script>
window.onload = function()
{
var oUl = document.getElementById("ul1");
for(var i=0; i<1000; i++)
{
var oLi = document.createElement('li');
oUl.appendChild(oLi);
}
};
script>
<body>
<ul id="ul1">
ul>
body>
html>
改用文档碎片:
<html>
<head>
<meta charset="utf-8" />
<title>title>
head>
<script>
window.onload = function()
{
var oUl = document.getElementById("ul1");
var oFrag = document.createDocumentFragment();
for(var i=0; i<1000; i++)
{
var oLi = document.createElement('li');
//oUl.appendChild(oLi);
oFrag.appendChild(oLi);
}
oUl.appendChild(oFrag);
};
script>
<body>
<ul id="ul1">
ul>
body>
html>