我正在尝试使用 JavaScript 创建 UL 元素并将其添加到 html 页面中的 div 但问题是当我将 UL 附加到 html 中的 div 时。我收到一个错误:
Uncaught TypeError: Cannot read property 'appendChild' of null
我尝试将它附加到正文和标题,它可以工作,但不能在 div 元素中。
谢谢!
HTML 代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>CodeError</title>
<meta name="description" content="This is an example of a meta description.">
<link rel="stylesheet" type="text/css" href="style.css">
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<div class='.main'></div>
</header>
<script src="index.js"></script>
</body>
</html>
Javascript代码:
const body = document.querySelector('.main');
const ul = document.createElement('ul');
const li = document.createElement('li');
li.innerHTML = 'Nico';
ul.appendChild(li);
body.appendChild(ul);
最佳答案
问题是:
<div class='.main'></div>
您的 JS 代码正在寻找一个具有“main”类的元素,点表示它是一个类这一事实。你的实际类名应该是'main',而不是'.main',所以:
<div class='main'></div>
此行引发错误:
body.appendChild(ul);
因为
body
此时为空。因为这一行:const body = document.querySelector('.main');
找不到带有
class='main'
的元素, 因为目前你有 class='.main'
.
关于javascript - 在 div 标签中使用 javascript 将 UL 添加到 HTML 时被捕获并出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59689618/