6

img

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

Thanks you.

O.Chounry
  • 304
  • 4
  • 16
  • 1
    This is not a code factory. Can you show us what you tried? – muecas Apr 22 '18 at 15:38
  • 1
    This is something you really shouldn't do. But theoretically, you can just call `document.appendChild()`. But, again, you shouldn't. All content on a page should be inside the body; putting content outside it can lead to upredictable behavior in different browsers. – Máté Safranka Apr 22 '18 at 15:40
  • I have tried,`document.appendChild()` but it's not working. – O.Chounry Apr 22 '18 at 15:40
  • Can you explain why you need this? Just curious. – ideaboxer Apr 22 '18 at 15:41
  • Why would you want this? – Duncan Lukkenaer Apr 22 '18 at 15:42
  • @muecas It is not a pure code factory, but still it is a code factory ;-) – ideaboxer Apr 22 '18 at 15:43
  • Because I think it would not affect by other css but itself. I have problem with the css. By the way I am building a Firefox extension. – O.Chounry Apr 22 '18 at 15:45
  • Possible duplicate of [Adding div element to body or document in JavaScript](https://stackoverflow.com/questions/15741006/adding-div-element-to-body-or-document-in-javascript) – Narendra Jadhav Apr 22 '18 at 15:45
  • 2
    @N.Jadhav : That would append to the body tag. – O.Chounry Apr 22 '18 at 15:50
  • 1
    If it's not `document.appendChild()` then there should be some property of `document` which corresponds to the HTML tag (it might be `documentElement`), so you can call `appendChild()` if you need to; try researching `window.document`. I would honestly recommend rethinking your CSS though, but it's your call. – Máté Safranka Apr 22 '18 at 15:51

2 Answers2

12

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>");
0

you can use this

var div = document.createElement("DIV");
div.id = "id";
div.innerHTML = "1223";
document.body.parentNode.insertBefore(div, document.body.nextSibling);
Emad Elpurgy
  • 347
  • 1
  • 3
  • 8