简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM