O.Chounry
O.Chounry

Reputation: 322

How to append element after the body tag?

img

This is what I want. I want the new created element append after the body tag.Not inside the body tag.

Thanks you.

Upvotes: 6

Views: 11232

Answers (2)

user2437417
user2437417

Reputation:

You can use document.documentElement to do the appending.

document.documentElement.appendChild(new_div);

This is how the <html> element is represented in the DOM.


This will not necessarily put it directly after the body. If that's needed, then you'd use .insertBefore instead of .appendChild.

document.documentElement.insertBefore(new_div, document.body.nextSibling);

Or you can use .insertAdjacentElement.

document.body.insertAdjacentElement("afterend", new_div);

If you're creating the new element using HTML markup in your JS, then you can use .insertAdjacentHTML.

document.body.insertAdjacentHTML("afterend", "<div>...</div>");

Upvotes: 12

Emad Elpurgy
Emad Elpurgy

Reputation: 357

you can use this

var div = document.createElement("DIV");
div.id = "id";
div.innerHTML = "1223";
document.body.parentNode.insertBefore(div, document.body.nextSibling);

Upvotes: 0

Related Questions