<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <div id="d1"> <div id="d1_1"></div> <div id="d1_2"></div> </div> <div id="d2">你好 <div id="d2_1">我是狗</div> <div id="d2_2"></div> </div> <table> <tr> <p> <td id="haha">haha</td> </p> </tr> </table> <script type="text/javascript"> var mylibs = { first:function(elem){ return elem && (elem.firstElementChild || elem.firstChild); }, last:function(elem){ return elem && (elem.lastElementChild || elem.lastChild); }, prev:function(elem){ return elem && (elem.previousElementSibling || elem.previousSibling); }, next:function(elem){ return elem && (elem.nextElementSibling || elem.nextSibling); }, before:function(newElement,targetElement){ return targetElement && targetElement.parentNode ? targetElement.parentNode.insertBefore(newElement,targetElement) : null; }, after:function(newElement,targetElement){ return targetElement && this.last(targetElement) == targetElement ? // 如果最后的节点是目标元素,则直接添加。因为默认是最后 this.before(newElement,targetElement) : //如果不是,则插入在目标元素的下一个兄弟节点 的前面。也就是目标元素的后面 this.before(newElement, this.next(targetElement)); }, replace:function(elem,newElement,oldElement){ }, remove:function(elem){ return elem.parentNode.removeChild(elem); }, empty:function(elem){ elem.innerHTML = ''; return elem; }, append:function(elem,newElement){ return elem.appendChild(newElement); }, text:function(elem,value){ return value === undefined ? elem.textContent || elem.innerHTML.replace(/<[^<]+>/g,'') : this.append(this.empty(elem),(elem && elem.ownerDocument || document).createTextNode(value)); }, html:function(elem,value){ if(value === undefined && elem.nodeType === 1) return elem.innerHTML; if(typeof value === 'string' && /<(?:script|style|link)/i.test(value)){ value = value.replace(/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,'<$1></$2>'); elem.innerHTML = value; } if(elem){ this.append(this.empty(elem),value); } } /*append() - 在被选元素的结尾插入内容 prepend() - 在被选元素的开头插入内容 after() - 在被选元素之后插入内容 before() - 在 remove() - 删除被选元素(及其子元素) empty() - */ }; var dom1 = document.getElementById('d1'), dom2 = document.getElementById('d2'); var tmp = document.createElement('div'); console.log(mylibs.after(tmp,dom2)); </script> </body> </html>