8

Let's say we have this markup:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf8" />
<title>project.js</title>
<script src="project.js"></script>
<script>

</script>
</head>

<body>
<h1>some project &mdash; javascript & html tests</h1>
<hr />

    <p>
        testing 123
    </p>
</body>
</html>

I know that there are .prependChild(), .appendChild(), .innerHTML, etc, properties and methods, but what I am looking for is how to add (append) contents after the </body> tag closure?

I need this, without using jQuery — is it possible?

  • I think most browser would not let you create an invalid DOM through DOM functions. (`html` can only contain 1 `head` and 1 `body` element and comment nodes. Nothing else.) – Roman Mar 08 '13 at 08:56
  • so meaning.. if I want to add something `after body` I should just then append the parent: `html` tag? –  Mar 08 '13 at 08:57
  • @ZlatanO. What do you want to add?! – Matías Fidemraizer Mar 08 '13 at 08:58
  • no.. that means if you try to add anything other than comments after the body tag, the browser will either ignore it or append it to `body`. – Roman Mar 08 '13 at 08:59
  • @MatíasFidemraizer - sorry matias, for not answering your question.. I've seen now that we can add scripts: `appended or prepended to **head**` or `appended or prepended to **body**` .. I'm making a script loader –  Mar 08 '13 at 09:02

2 Answers2

8

If you use 'id'.you can use these property:

document.getElementById('id').nextSibling; 
document.getElementById('id').previousSibling;
Amrendra
  • 2,019
  • 2
  • 18
  • 36
  • 3
    Worth to mention, if there's a whitespace between the elements the `nextSibling` will return `undefined`. See this example here: http://www.w3schools.com/code/tryit.asp?filename=FBONDLQCJA0W – Ram Patra Jan 12 '17 at 23:27
2

It won't work in some browser because content after body is not "legal". Anyway, this would be:

document.body.parentNode.appendChild(document.createTextNode('text after body'));
document.body.parentNode.appendChild(document.createComment('comment after body'));

http://jsfiddle.net/yVKk6/ and inspect the Result frame.

Roman
  • 5,888
  • 26
  • 47
  • because of some unexplainable reason I tought we can add scripts after the `

    ` statement, but now I realized they're either appended / prepended to `body` or `head`!

    –  Mar 08 '13 at 09:12