user3389343
user3389343

Reputation: 63

Javascript Accessing dom element directly and using a variable

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?

Upvotes: 1

Views: 216

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1075587

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().

Upvotes: 0

Mohammed R. El-Khoudary
Mohammed R. El-Khoudary

Reputation: 1203

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.

Upvotes: 1

Related Questions