插入和添加子节点

DOM 中的 appendChild 和 insertBefore 用于插入某个节点的子节点。其中 appendChild 用于在最后一个子节点之后添加新节点,例如:

var showarea = document.getElementById("showarea");
var node = document.createElement("div");
node.innerHTML = "this is a new node";
showarea.appendChild(node);

而 insertBefore 用于在某个子节点之前插入新节点,例如下面的例子在 showarea 节点的第2个子节点前面插入一个新的 div 节点:

var showarea = document.getElementById("showarea");
var node = document.createElement("div");
node.innerHTML = "this is a new node";
showarea.insertBefore(node, showarea.childNodes[2]);

一般来说 insertBefore 用得比较多。其中有一个问题需要注意,就是下面这种情形:

showarea.insertBefore(node, showarea.childNodes[showarea.childNodes.length]);

看起来是想用 insertBefore 来代替 appendChild 的功能。上面的代码在 Firefox 和 Chrome 中都能运行,而在 IE6 和 IE8 中都报错。这是因为此时

showarea.childNodes[showarea.childNodes.length] = undefined

对于 insertBefore 函数的第2个参数,如果它是 undefined 或者 null, Firefox 和 Chrome 都会在最后面添加子节点,而 IE 只会对该参数为 null 时才会这样做。因此,上面的代码稍微修改就可以解决这个问题了:

showarea.insertBefore(node, showarea.childNodes[showarea.childNodes.length] || null);

这是因为

undefined || null = null

参考资料:
[1] JavaScript之appendChild、insertBefore和insertAfter
[2] Node.appendChild - MDM
[3] Node.insertBefore - MDM

原文地址:https://www.cnblogs.com/zoho/p/2434862.html