<html>
...
<body>
...
// element should be inserted here
</body>
</html>
I'm not very familiar with vanilla Javascript, always have worked with jQuery. I tried this so far, but that got the element in the middle of <head>
and <body>
.
var bodyTag = document.getElementsByTagName('body')[0];
bodyTag.parentNode.insertBefore(myElement, bodyTag);
It's pretty simple. Using appendChild method it can be written as short as:
document.body.appendChild(myElement);
This works:
document.body.insertAdjacentHTML("beforeend", inserted_elements);
The insertAdjacentHTML should work here. You can specify where you want to insert the new HTML: beforebegin, afterbegin, beforeend and afterend.
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
In your case:
document.body.insertAdjacentHTML("beforeend", myElement);
document.body.insertAdjacentHTML("beforeend", "<h2>Hello World!</h2>");
Remember that insertAdjacentHTML accepts the raw HTML. You can pass the HTML node with myElement.outerHTML.
You can read more about insertAdjacentHTML here: MDN
If you want to insert a HTML node straight away use: document.body.appendChild(myElement);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.