How to get next element using JavaScript-only?

2019-04-07 07:14发布

问题:

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?

回答1:

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

document.getElementById('id').nextSibling; 
document.getElementById('id').previousSibling;


回答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.