I'm trying to create UL element using JavaScript and adding it to div in html page but the problem is when I'm appending the UL to a div in html. I get an error:
Uncaught TypeError: Cannot read property 'appendChild' of null
I tried appending it to body and header and it works but not in a div element.
Thank you!
HTML Code:
<!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 Code:
const body = document.querySelector('.main');
const ul = document.createElement('ul');
const li = document.createElement('li');
li.innerHTML = 'Nico';
ul.appendChild(li);
body.appendChild(ul);
The problem is:
<div class='.main'></div>
Your JS code is looking for an element with class 'main', the dot represents the fact that it's a class. Your actual class name should be 'main', not '.main', so:
<div class='main'></div>
The error is thrown by this line:
body.appendChild(ul);
Because body
is null at this point. Because this line:
const body = document.querySelector('.main');
Fails to find an element with class='main'
, because currently you have class='.main'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With