The element can be anything like a <div> or a <p> etc., which you are creating dynamically. To add the dynamically created element to the <body> selection of your web page, you can use the body property of the "document" object. For example,
<body>
</body>
<script>
let add_element = () => {
const template = document.createElement('div'); create DIV element.
template.innerHTML = "Content inside DIV";
document.body.appendChild(template); Now, add element to the BODY.
}
add_element();
</script>The "body" property (in the above example) sets or returns the document's (the web page) body element. The appendChild() method adds (or appends) the element (a <div> element in this case) to the body of the document.
The <body> section (in the above example) had no other element, before I created a DIV element. The BODY can have other elements, and you can still use "appendChild()" to add a new element to the BODY.
Now, try this example,
<body>
<div>
Hello, I am Arun Banik!
</div>
</body>
<script>
let add_element = () => {
const template = document.createElement('div');
template.innerHTML = "I am a blogger";
document.body.appendChild(template); Append element to the BODY.
}
add_element();
</script>This you should know
Many programmers, I have seen in the past, use the innerHTML property to add an element to the <body> section. For example,
const template = document.createElement('div'); template.innerHTML = "Hello there…"; document.body.innerHTML = template.innerHTML; or document.body.innerHTML = '<div>Hello there...</div>';
Remember, this will overwrite the existing contents inside the <body> section. The innerHTML property will change the HTML contents (with new contents) of the body. So, if you want to add a new element to the exiting elements in the BODY, then use appendChild() method.
🚀 You may also like this... How to add another Class name to an element (which already has a class) using JavaScript
Using insertBefore Method
Here's another method that you can use to add a newly created element to the <body>.
The insertBefore() method, adds an element before an existing element. So, you can add a newly created element before an already existing element inside the <body> element.
<body>
<div id='d1'> I am Arun Banik! </div>
</body>
<script>
let add_element = () => {
const template = document.createElement('div');
template.innerHTML = "Hello there,";
document.body.insertBefore(template, document.getElementById('d1'));
}
add_element();
</script>