How to Add Element to body using JavaScript

← PrevNext →

You can use the .appendChild() method in JavaScript to add or append an element to the body section of a document or a web page.

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');
    template.innerHTML = "Content inside DIV";
    
    document.body.appendChild(template);
}

add_element();
</script>
Try it

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 our case) to the body of the document.

The <body> section in the above example has no other element, before I created a DIV element dynamically. You can however have an element inside the <body> and the appendChild() method will append the newly created <div> with the existing element(s).

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);
}

add_element();

</script>
Try it

Note: 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 or append any newly created element, I recommend using the appendChild() method. See the examples above.

Using insertBefore Method

Well, this is optional, however useful. 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>
Try it

That's it. Thanks for reading.

← PreviousNext →