0

Would anyone know why I’m able to get my code to run on codepen, but not on my desktop? I keep getting a “can't read appendChild” error when I run my code on my desktop. I am new to coding and just started teaching my self how to manipulate the DOM.

https://codepen.io/unicorn1/pen/JpYqjJ

const container = document.querySelector('#container');
const content = document.createElement('div');
content.classList.add('content');
content.textContent = 'Dom text-content!';
container.appendChild(content);

Error Message

enter image description here

Prakhar Agarwal
  • 2,310
  • 23
  • 30
  • 3
    Where have you positioned your JS in desktop code? It matters. Ideally have your JS at the bottom just before the body ends – cdoshi Feb 02 '18 at 05:38

1 Answers1

0

the script should be put at the bottom before the body ends

<html>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <h1>
    THE TITLE OF YOUR WEBPAGE
  </h1>
    <div id="container"></div>
    <script>
    const container = document.querySelector('#container');

    const content = document.createElement('div');
    content.classList.add('content');
    content.textContent = 'Dom text-content!';

    container.appendChild(content);
    </script>
</body>

</html>

or you can put the content of script in the window.onload callback like this:

<html>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <script>
    window.onload = function() {
        const container = document.querySelector('#container');

        const content = document.createElement('div');
        content.classList.add('content');
        content.textContent = 'Dom text-content!';

        container.appendChild(content);

    };
    </script>
    <h1>
        THE TITLE OF YOUR WEBPAGE
      </h1>
    <div id="container"></div>
</body>

</html>

the principle is that,you can manipulate DOM after the DOM have loaded;you can't manipulate DOM before loaded.that is how window.onload and script position works; also ,you can change the window.onload to DOMContentLoaded

<html>

<head>
    <meta charset="UTF-8">
</head>

<body>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const container = document.querySelector('#container');

        const content = document.createElement('div');
        content.classList.add('content');
        content.textContent = 'Dom text-content!';

        container.appendChild(content);

    }, false);
    </script>
    <h1>
            THE TITLE OF YOUR WEBPAGE
          </h1>
    <div id="container"></div>
</body>

</html>
xianshenglu
  • 4,009
  • 1
  • 10
  • 25