Home > Software engineering >  How to add an HTML element found by ID to the body?
How to add an HTML element found by ID to the body?

Time:01-26

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;

CodePudding user response:

There are a few options.

  • Option 1 : clear the content of <body> and append your element as a child.

var el = document.getElementById("one");
document.body.innerHTML = ''; // Clears the body inner HTML
document.body.appendChild(el) // Appends your element as a child
<div id="one">
 HELLO
</div>
GOOD BYE CONTENT

  • Option 2 : Replace children of <body> with your element.

var el = document.getElementById("one");
document.body.replaceChildren(el); // Replace the body content by your element
<div id="one">
 HELLO
</div>
GOOD BYE CONTENT

CodePudding user response:

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>

CodePudding user response:

With append or replaceChildren you can reach this.

const tag = document.querySelector('#email');
const w = document.createElement('div');
w.append(tag)
document.querySelector('body').innerHTML = '';
document.querySelector('body').append(w);
<html>
  <head>Head</head>
  <body>
    <h1>body</h1>
    <div id="email"> EMAIL </div>
  </body>
</html>

const tag = document.querySelector('#email');
document.querySelector('body').replaceChildren(tag);
<html>
  <head>Head</head>
  <body>
    <h1>body</h1>
    <div id="email"> EMAIL </div>
  </body>
</html>

  • Related