4

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);
1
  • Protip: Tags and elements are not the same thing. A tag is markup in your text file. An element is part of the document model. It's best to use the correct terminology. Commented Jan 10, 2020 at 22:16

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

Comments

2

CSS class name Naming rules:

  • Must begin with a letter A-Z or a-z
  • Can be followed by: letters (A-Za-z), digits (0-9), hyphens ("-"), and underscores ("_")

Change This:

<div class='.main'></div>

To This:

<div class='main'></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.