Search code examples
javascriptdomclone

Remove a dom element from the document, but save it as a variable?


Is there a way to remove a dom element from the document, but save it as a variable? I'm guessing I have to save the clone as a var, and then remove the original?

Also, would such a technique store styles etc?


Solution

  • Yes, that's what you do.

    var savedElement = document.getElementById('element_that_you_want_to_save');
    savedElement.parentNode.removeChild(savedElement);
    
    // savedElement will still contain the reference to the object,
    // so for example, you can do:
    savedElement.style.height = '100px';
    document.getElementById('container').appendChild(savedElement);
    // etc.