使用insertBefore&时出错在创建元素时使用appendChild

时间:2017-03-30 14:30:12

标签: javascript

尝试在身体标签的顶部和底部添加一个按钮,但它只执行两个中的任何一个是最后一个。我错过了一些明显的东西吗?

var msg_node = document.createElement("a");
msg_node.setAttribute("onclick", "collapseAll()");
msg_node.setAttribute("href", "javascript:void(0)");
msg_node.setAttribute("class", "kc_button");
var msg_textnode = document.createTextNode('COLLAPSE ALL');
msg_node.appendChild(msg_textnode);
document.getElementsByTagName('body')[0].appendChild(msg_node);  // supposed to make button
document.body.insertBefore(msg_node, document.body.children[0]); // makes only this button

1 个答案:

答案 0 :(得分:2)

在第二次附加节点之前克隆节点:

var msg_node = document.createElement("a");
msg_node.setAttribute("onclick", "collapseAll()");
msg_node.setAttribute("href", "javascript:void(0)");
msg_node.setAttribute("class", "kc_button");
var msg_textnode = document.createTextNode('COLLAPSE ALL');
msg_node.appendChild(msg_textnode);
document.getElementsByTagName('body')[0].appendChild(msg_node);  // supposed to make button
document.body.insertBefore(msg_node.cloneNode(true), document.body.children[0]); // makes only this button