1

Trying to append a button to both the top and bottom of the body tag, however it's only performing whichever one of the two is last. Am I missing something obvious here?

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
3
  • 1
    Possible duplicate of How to add multiple divs with appendChild? - As the accepted answer here states, you've only created one element. If you want to create two, you need to call createElement twice. Commented Mar 30, 2017 at 14:35
  • Thanks, this makes sense. Can I do something like var msg_node_2 = msg_node; or do i have to repeat the entire code over again? Commented Mar 30, 2017 at 14:46
  • 1
    You can do var msg_node_2 = msg_node.cloneNode(true); as Matansh's answer points out. Commented Mar 30, 2017 at 14:55

1 Answer 1

2

Clone the node before appending it the second time:

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
Sign up to request clarification or add additional context in comments.

4 Comments

by cloning, can I do something like var msg_node_2 = msg_node;?
No, because msg_node is an object, and copy its reference into a new variable won't do the trick. The cloneNode works great, try it.
By the way, cloneNode will also copy the onclick, href and class attributes, if that is what you are worry about.
cloneNode worked perfectly! Thank you. As per the docs, it copied all children (attributes, etc).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.