How to get next element using JavaScript-only?

我们两清 提交于 2019-12-05 22:56:45

问题


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.



来源:https://stackoverflow.com/questions/15289932/how-to-get-next-element-using-javascript-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!