Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caught and error in adding UL using javascript to HTML in div tag

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);
like image 258
nicolo orcine Avatar asked Dec 23 '22 19:12

nicolo orcine


1 Answers

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'.

like image 133
Zeal Avatar answered Jan 24 '23 14:01

Zeal