1

This is my HTML :

<html>
<head>
<script src="domManipulating.js"></script>    
</head>

// The DOM
<body>
  <h1>
    THE TITLE OF YOUR WEBPAGE
  </h1>
  <div id="container">
    <div class="content">
      This is the glorious text-content!
    </div>
  </div>
</body>

</html>

And this is my JS

var content = document.querySelector(".content");
var paragraph = document.createElement("p");

paragraph.textContent = " Hey I'm red";

content.appendChild(paragraph);

When I use the console to test my code a error appears :

Uncaught TypeError: Cannot read property 'appendChild' of null 

From my understanding the variable content can't hold document.querySelector(".content")

When I write document.querySelector(".content")in the console it actually works but when I use var paragraph = document.createElement("p");the variable turns into a null.

Why is that happening?

Plínio Helpa
  • 115
  • 1
  • 6

2 Answers2

2

The issue seems to be with <script src="domManipulating.js"></script> loading before DOM is ready. In that case document.querySelector will not able to find the element from the DOM

One alternative is to load the script just before closing body tag

<body>
   //html tags
<script src="domManipulating.js"></script>
</body>

var content = document.querySelector(".content");
var paragraph = document.createElement("p");

paragraph.textContent = " Hey I'm red";

content.appendChild(paragraph);
<h1>
  THE TITLE OF YOUR WEBPAGE
</h1>
<div id="container">
  <div class="content">
    This is the glorious text-content!
  </div>
</div>
brk
  • 43,022
  • 4
  • 37
  • 61
1

Look at the location of your script tag in your HTML: it's above the body. At the time the script runs, the body (and all of its content, including .content) has not been created yet.

Either wrap your whole script in a function that runs once the document is loaded:

document.addEventListener('DOMContentLoaded', () => {
  var content = document.querySelector('.content');
  // ...

or, a better option: give your script the defer attribute, and it'll automatically run only once the document is ready to be parsed:

<head>
<script src="domManipulating.js" defer></script>
</head>
CertainPerformance
  • 260,466
  • 31
  • 181
  • 209