有谁知道为什么我能够让我的代码在codepen上运行,但不能在我的桌面上运行?当我在桌面上运行代码时,我不断收到“无法读取appendChild”错误。我是编码新手,刚开始教自己如何操纵DOM。
https://codepen.io/unicorn1/pen/JpYqjJ
const container = document.querySelector('#container');
const content = document.createElement('div');
content.classList.add('content');
content.textContent = 'Dom text-content!';
container.appendChild(content);
错误消息
答案 0 :(得分:0)
脚本应该在正文结束之前放在底部
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container"></div>
<script>
const container = document.querySelector('#container');
const content = document.createElement('div');
content.classList.add('content');
content.textContent = 'Dom text-content!';
container.appendChild(content);
</script>
</body>
</html>
或者您可以将脚本的内容放在window.onload回调中,如下所示:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
window.onload = function() {
const container = document.querySelector('#container');
const content = document.createElement('div');
content.classList.add('content');
content.textContent = 'Dom text-content!';
container.appendChild(content);
};
</script>
<h1>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container"></div>
</body>
</html>
原则是,你可以在DOM加载后操作DOM;你不能在加载之前操纵DOM。这就是window.onload和脚本位置的工作方式; 另外,您可以将window.onload更改为DOMContentLoaded
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<script>
document.addEventListener('DOMContentLoaded', function() {
const container = document.querySelector('#container');
const content = document.createElement('div');
content.classList.add('content');
content.textContent = 'Dom text-content!';
container.appendChild(content);
}, false);
</script>
<h1>
THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container"></div>
</body>
</html>