Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add an HTML element found by ID to the body?

I want to add an DOM element that is found by ID into the body tag and remove all ewxisting body nodes.

My solution does not work:

var ele = document.getElementById("email");
document.body.innerHTML = ele;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This:

document.body.innerHTML = ele;

Will interpret ele as a string and write that string to the document body. That string is going to be something like "[object HTMLDivElement]" (may differ by browser).

and remove all ewxisting body nodes

It sounds like you’re looking for document.body.replaceChildren() then? For example:

var ele = document.getElementById("email");
document.body.replaceChildren(ele);
<div>test 1</div>
<div id="email">test 2</div>
<div>test 3</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading