How to get next element using JavaScript-only?
Asked Answered
W

2

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?

Welltodo answered 8/3, 2013 at 8:45 Comment(5)
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.)Condorcet
so meaning.. if I want to add something after body I should just then append the parent: html tag?Welltodo
@ZlatanO. What do you want to add?!Chrysarobin
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.Condorcet
@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 loaderWelltodo
C
8

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

document.getElementById('id').nextSibling; 
document.getElementById('id').previousSibling;
Carlist answered 8/3, 2013 at 8:50 Comment(1)
Worth to mention, if there's a whitespace between the elements the nextSibling will return undefined. See this example here: w3schools.com/code/tryit.asp?filename=FBONDLQCJA0WManufactory
C
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.

Condorcet answered 8/3, 2013 at 9:7 Comment(1)
because of some unexplainable reason I tought we can add scripts after the </body> statement, but now I realized they're either appended / prepended to body or head!Welltodo

© 2022 - 2024 — McMap. All rights reserved.