Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to move an element from one place to another in the DOM using plain JavaScript?

Tags:

javascript

I know how to do it in jQUery (untested but should work):

$('#foo').html().appendTo('#bar');
$('#foo').remove();

But how to do this in plain JS?


2 Answers

field = document.getElementById('e');
document.getElementById('x').innerHTML = field.parentNode.innerHTML;
field.parentNode.removeChild(field);

this is ONE solution, you can search for clonenode too.

like image 72
Toping Avatar answered Oct 21 '25 14:10

Toping


Your jQuery code can be done like this in plain javascript:

var foo = document.getElementById("foo"),
    bar = document.getElementById("bar");
bar.innerHTML = foo.innerHTML;
foo.parentNode.removeChild(foo);

But this just copies the html code inside foo to bar as a string, then removes foo from the DOM.

Moving the nodes is also possible, like this:

var foo = document.getElementById("foo"),
    bar = document.getElementById("bar");
bar.innerHTML = "";
for (var node in foo.childNodes) {
    bar.appendChild(node);
}
foo.parentNode.removeChild(foo);

This will move the actual child nodes of foo to bar, and then remove the now empty foo.

like image 38
aorcsik Avatar answered Oct 21 '25 12:10

aorcsik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!