0

This is my index.html:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="style.css" type="text/css">
    </head>
    <body>
        <script src="app.js"></script>
        <h1>The fantastic website</h1>
        <h2>A humble experience</h2>
        <div id="hold">
            <p>Test! And test again!</p>
        </div>
    </body>
</html>

This is my app.js:

const thediv = document.getElementById('hold');

console.log(thediv);

When I access the page and look to the console, I see this: Console showing "null"

When I repeat this same app.js code in the console, I can select the element. But using this code, I just get "null". What am I missing here?

  • 3
    use ``, with that explicit [defer attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer), because your script should run _after_ your DOM has been built, not before. – Mike 'Pomax' Kamermans Oct 20 '19 at 02:10

2 Answers2

1

Your console is outputting null because at the time your javascript is being run, the hold element isn't yet available in the DOM.

Move your script to the bottom of the page and it should work.

MMM
  • 307
  • 8
  • 18
  • It happens in my case when i try to select an element inside a web component, i tried adding the script AFTER 4 seconds and IF the web component is shown, but instead of returing the element, it returns the number: 1 I wonder if it could be because of shadow DOM – Code Drop Jun 28 '22 at 16:55
1

Try putting your import to the app.js after the DOM has been defined.

You may be trying to access the document before it has finished loading. That's why some people put some scripts before the end of the body tag.

dsapalo
  • 1,819
  • 2
  • 19
  • 37