JS插入新的节点

本文介绍了DOM操作中的几种关键方法:insertBefore(), appendChild()及自定义的insertAfter()方法。通过具体的JavaScript示例展示了如何使用这些方法来动态地在HTML文档中插入元素。

insertBefore()

语法:

insertBefore(newchild,refchild)

newchild 插入新的节点

refchild 在此节点前插入新节点

 

<ul id="myList">

  <li>Coffee</li>

  <li>Tea</li>

</ul>

 

function myFunction(){

    var newItem=document.createElement("LI")

    var textnode=document.createTextNode("Water")

    newItem.appendChild(textnode)

    var list=document.getElementById("myList")

    list.insertBefore(newItem,list.childNodes[0]);

}

 

appendChild()

语法:

appendChild(newchild)

newchild 所添加的节点

 

<ul id="myList">

<li>Coffee</li>

<li>Tea</li>

</ul>

 

function myFunction(){

      var node=document.createElement("LI");

      var textnode=document.createTextNode("Water");

      node.appendChild(textnode);

      document.getElementById("myList").appendChild(node);

}

 

 

js写基础insertAfter()方法

//DOM没有提供insertAfter()方法

function insertAfter(newElement, targetElement){

     var parent = targetElement.parentNode;

     if (parent.lastChild == targetElement) {

// 如果最后的节点是目标元素,则直接添加。因为默认是最后

          parent.appendChild(newElement);

   }else {

         parent.insertBefore(newElement, targetElement.nextSibling);

//如果不是,则插入在目标元素的下一个兄弟节点 的前面。也就是目标元素的后面

    }

}

 

转载于:https://www.cnblogs.com/ranyonsue/p/7759996.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值