1

Why is doing

var consoleElem = document.getElementById("debug");
consoleElem.appendChild(msgElement)

the same thing as

document.getElementById('debug').appendChild(msgElement);

It seems to me that the DOM element (debug) is its own variable, and then to copy it to another variable means I have two copies of the debug element... why should any changes I make to the new copy (var consoleElem) make changes to the original DOM element?

1
  • 2
    It doesn't copy it. It only creates a reference to the element. To copy you have to call cloneNode() I believe. Commented Mar 6, 2014 at 17:28

2 Answers 2

1

What is in the consoleElem isn't the DOM element itself but instead a reference to it.. so any change that's done through the reference is actually applied to the DOM element itself..

If you want to modify an element without actually changing the original element itself then you should clone it.. jQuery offers a clone functionality.

Sign up to request clarification or add additional context in comments.

Comments

0

The call document.getElementById returns a reference to a DOM element. All that the line

var consoleElem = document.getElementById("debug");

does is store that reference in a variable; it doesn't create anything. You can have a dozen variables referring to the same element, and it's still just one element.

If you want to create an element, use document.createElement. If you want to copy an element, use newElement = oldElement.cloneNode().

Comments

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.