js 添加 移除 替换 插入

添加、移除、替换、插入

appendChild() //添加

removeChild() //移除

replaceChild() //替换

insertBefore() //插入

<script>
window.onload=function(){
// var box=document.getElementById("box");
//添加 appendChild() 先用createElement()创建元素
// var span=document.createElement("span")
// span.innerHTML="haha";
// box.appendChild(span);
//
//删除 removeChild() 
// var p=box.getElementsByTagName("p")[0];
// box.removeChild(p)


//替换replaceChild() 先用createTextNode()创建内容
// var p=box.getElementsByTagName("p")[0];
// var newp=document.createTextNode("修改了")
// box.replaceChild(newp,p)
//插入  insertBefore 一个是节点,第二个是位置
//第一种方法 先创建元素 
// var span=document.createElement("span");
// span.innerHTML="哈哈";
// box.insertBefore(span,box.childNodes[0])
//第二种方法 把其他节点移到另一个节点 
// var box2=document.getElementById("box2");
// box.insertBefore(box2,box.childNodes[0])
//如果不要把整个都拿过来,可以取节点下面的元素
// var list2=document.getElementById("list").lastChild;
// var list=document.getElementById("list2");
// list.insertBefore(list2,list.childNodes[0]);
//          比较了下appendChild 跟 insertBefore 一个是添加在后面,一个是插入,插入在前面。

}
</script>

<body>
<div id="box">
<p>第一个</p>
</div>
<div id="box2">
<p>第二个</p>
</div>
<ul id="list"><li>1x</li><li>1</li></ul>
<ul id="list2"><li>2</li><li>2</li></ul>

</body>

猜你喜欢

转载自blog.csdn.net/qq_36273128/article/details/53049469