Get empty nodelist when run with vs code

I try to run script from VS code , it always show empty nodelist but when I run with chrome console it works properly. Please give me some advice if I’m doing it wrong.

How are you running the script in the HTML, when does the code run? Is the DOM ready?

Try wrapping the code inside a DOMContentLoaded handler.

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="app.js">

I try to use DOM method to the webpage.
This is how I linked js file to the HTML file(It’s in the same folder). When I run on local or on server (with vscode) it looks like js file doesn’t link on HTML file but when I write the same code on developer tool console it works fine.

Hey @beerbluedevils,

Looks like you got the case of putting the JavaScript on the head. This will not work because the javascript will run BEFORE the DOM is loaded. What you need to do is put it at the end, before the </body> ends like this:


<!-- HTML -->

<script src="app.js"></script>

Another solution is to add the defer attribute inside the script tag, so it will run after the DOM is loaded. like this: <script defer src="app.js"></script>

Hope this helps :slight_smile:

It works! Thank you very much. I have one more question.
Does the place of the script matter? For example : if I want to run script after the

I need to put it after that not on the head.

Yes, the position of the script does actually matter… Let’s say you want to run a function from a different file, you have to put the script that have the function on top of the script that you want to run the function in. That’s why when library is being used, it will often be on top of the main JavaScript file.

1 Like

Thank you very much.