js操作DOM--添加、删除节点

13 篇文章 0 订阅
8 篇文章 0 订阅

js removeChild() 用法

<body>
<p id="p1">welcome to <b>javascript</b> world !</p>
<script language="javascript" type="text/javascript">
<!--
function nodestatus(node)
{
  var temp="";
  if(node.nodeName!=null)
  {
    temp+="nodeName="+node.nodeName+"\n";
  }
  else temp+="nodeName=null \n";
  if(node.nodeType!=null)
  {
    temp+="nodeType="+node.nodeType+"\n";
  }
  else temp+="nodeType=null \n";
  if(node.nodeValue!=null)
  {
    temp+="nodeValue="+node.nodeValue+"\n";
  }
  else temp+="nodeValue=null \n";
  return temp;
}
var parent=document.getElementById("p1");
var msg="父节点 \n"+nodestatus(parent)+"\n";
//返回元素节点p的最后一个孩子
last=parent.lastChild;
msg+="删除之前:lastChild--"+nodestatus(last)+"\n";
//删除节点p的最后一个孩子,变为b
parent.removeChild(last);
last=parent.lastChild;
msg+="删除之后:lastChild--"+nodestatus(last)+"\n";
alert(msg);
-->
</script>
</body>

 

---------------------------------------------------------------------------------------------------------------------------------

=================================================================

<html>

<head>

<title>js控制添加、删除节点</title>

</head>
<script type="text/javascript">
    var all;
    function addParagraph() {
        all = document.getElementById("paragraphs").childNodes;
        var newElement = document.createElement("p");
        var seq = all.length + 1;
       
        //创建新属性
        var newAttr = document.createAttribute("id");
        newAttr.nodeValue = "p" + seq;
        newElement.setAttribute(newAttr);
       
        //创建文本内容
        var txtNode = document.createTextNode("段落" + seq);
       
        //添加节点
        newElement.appendChild(txtNode);
        document.getElementById("paragraphs").appendChild(newElement);
    }
    function delParagraph() {
        all = document.getElementById("paragraphs").childNodes;
        document.getElementById("paragraphs").removeChild(all[all.length -1]);
    }
</script>
<style>
    p{
        background-color : #e6e6e6 ;
    }
</style>
<body>
<center>
    <input type="button" value="添加节点" οnclick="addParagraph();"/>
    <input type="button" value="删除节点" οnclick="delParagraph();"/>
    <div id="paragraphs">
        <p id="p1">段落1</p>
        <p id="p2">段落2</p>
    </div>
</center>
</body>

</html>

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值