把节点newElement插入到节点targetElement节点的后面
function insertAfter(newElement,targetElement){ var parent = targetElement.parentNode; if(parent.lastChild == targetElement){ parent.appendChild(newElement); }else{ parent.insertBefore(newElement,targetElement.nextSibling); } }
例子,在#b后面插入一个新的li
1 <body> 2 <ul> 3 <li draggable="true">aa</li> 4 <li id="b">bb</li> 5 <li>ss</li> 6 </ul> 7 <script> 8 var target=document.getElementById("b"); 9 var newLi=document.createElement("li"); 10 var text=document.createTextNode("新的li内容"); 11 target.appendChild(newLi); 12 newLi.appendChild(text); 13 insertAfter(newLi,b); 14 function insertAfter(newElement,targetElement){ 15 var parent = targetElement.parentNode; 16 if(parent.lastChild == targetElement){ 17 parent.appendChild(newElement); 18 }else{ 19 parent.insertBefore(newElement,targetElement.nextSibling); 20 } 21 } 22 </script> 23 </body>
时间: 2024-12-17 10:31:50