如何仅使用javascript获取下一个元素

How to get next element using JavaScript-only?

本文关键字:下一个 元素 获取 javascript 何仅使      更新时间:2023-09-26

假设我们有这样的标记:

<!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>

我知道有.prependChild(), .appendChild(), .innerHTML等,属性和方法,但我要找的是如何在</body>标签关闭后添加(追加)内容?

我需要这个,不使用jQuery —这可能吗?

如果您使用'id'。您可以使用以下属性:

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

在某些浏览器中无法工作,因为body之后的内容不"合法"。无论如何,这将是:

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

http://jsfiddle.net/yVKk6/并检查结果框架