Sun Jan 09 2022·2 min read
Photo by Ishan Gupta
To insert an element into the body tag:
document.bodyproperty to get access to the body element.
appendChild()method on the body, passing it the element as a parameter.
Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box" style=" background-color: salmon; color: white; width: 150px; height: 150px; " > Box Content </div> <script src="index.js"></script> </body> </html>
const div1 = document.createElement('div'); div1.innerHTML = `<span style="background-color: lime;">Last element</span>`; // ✅ Insert element as last in body document.body.appendChild(div1); const div2 = document.createElement('div'); div2.innerHTML = `<span style='background-color: pink;'>First element</span>`; // ✅ Insert element as first in body document.body.insertAdjacentElement('afterbegin', div2);
We used the
method to create 2
div before inserting the elements into the body.
The appendChild method adds a node as the last child to the element it was called on.
We called the method on the
property to append the
div as the last child of the
The second example uses the insertAdjacentElement method.
const div2 = document.createElement('div'); div2.innerHTML = `<span style='background-color: pink;'>First element</span>`; // ✅ Insert element as first in body document.body.insertAdjacentElement('afterbegin', div2);
The method takes the following 2 parameters:
position - the position relative to the target element of where the passed
in element should be inserted. Can be one of the following:
beforebegin- before the target element itself.
afterbegin- just inside the target element, before its first child.
beforeend- just inside the target element, after its last child.
afterend- after the target element itself.
element - the element to be inserted into the tree.
divjust inside of the
bodyelement, before its first child, however you can change the
positiondepending on your use case.
insertAdjacentElement method can be called on any DOM element, it doesn't
have to be the
afterendvalues for the
If I open the example from the code snippet in my browser, I can see that the elements were inserted into the body tag.
And here is a screenshot of how the elements appear on the screen.
I'll send you 1 email a week with links to all of the articles I've written that week