#ReferenceError in JS

1 messages · Page 1 of 1 (latest)

oblique leaf
#

I'm having an issue when using document.querySelectorAll("select") to link to my HTML code and I'm not sure why


// Linking quotes_list.csv file to main

const fs = require('fs');

// Read the CSV file
fs.readFile('quotes_list.csv', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading the file:', err);
    return;
  }

  // Split the CSV data into rows
  const rows = data.split('\n');

  // Initialize an array to store the parsed data
  const dataArray = [];

  // Loop through each row and split it into columns
  for (let i = 0; i < rows.length; i++) {
    dataArray.push(rows[i]);
  }

  // Print the parsed data array
  console.log(dataArray);
});

//Link HTML to JavaScript
let selectMenu = document.querySelectorAll("select");

//Main code
for (let i = 12; i < 0; i--) {
    i = i < 10 ? "0" + i : i;
    let option = `<option value="${i}">${i}</option>`;
    selectMenu[0].firstElementChild.insertAdjacentHTML("afterend", option);
}```
-
``` HTML
<html>
    <head>
        <title>Motivational Alarm</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
<body>
    <div class="wrapper">
        <h1>12:23:30 AM</h1>
        <div class="content">
            <div class="column">
                <select>
                    <option value="Hour" selected hidden>Hour</option>
                </select>
            </div>
            <div class="column">
                <select>
                    <option value="Minute" selected hidden>Minute</option>
                </select>
            </div>
            <div class="column">
                <select>
                    <option value="AM/PM" selected hidden>Hour</option>
                </select>
            </div>
        </div>
        <button>Set Alarm</button>
    </div>

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

</body>
</html>```

This is the full error I get.

``` JavaScript
Uncaught ReferenceError ReferenceError: document is not defined
    at <anonymous> (file:///C:/Users/Praze/PROJECTS/Motivation%20Project/VersionOne/main.js:28:18)
    at Module._compile (node:internal/modules/cjs/loader:1254:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at executeUserEntryPoint (node:internal/modules/run_main:81:12)
    at <anonymous> (node:internal/main/run_main_module:23:47)
somber warren
#

Not sure if this is the answer but have you tried:

HTML: html <select id="id"> /// Everything else here </select>

JS: js let selectMenu = document.getElementById("id");

oblique leaf
somber warren
#

I wanna say I know what’s wrong, but I have doubts

fallen hound
#

Can you give a bit more information about your project? document is part of the DOM API but the DOM API isn't part to JavaScript itself, it's a web browser component and JS only allows you to access the object, however if you are trying to call it outside of a web browser, it will not work. Is it possible that your code or some of it isn't used in a web context?

oblique leaf
fallen hound
# oblique leaf This part of the project is building an alarm clock, so I was using JavaScript t...

Yea it's most likely due to node since node doesn't run in the browser and thus doesn't have a document object. So, to fix this you need to think about why you're trying to access a "browser object" from the server.

If it's a case where your code is used on both front-end and server you can simply add a condition to run this only if the document is present. It should fix the issue. However, this is a "hack" because in most cases, your code for the front-end and your server shouldn't be in at same place or get executed together.

if (typeof document !== 'undefined') {
  let ... = document.querySelector(...);

  ...
}
oblique leaf
fallen hound
#

Globally the idea is to separate your server logic from your front end logic (html, css, and the js for your front end). After that it really depends on the context. Just note that usually you want your server and client separated otherwise you get issues like that (and more anoying ones), it becomes really difficult maintain, etc.

You might want to look into the MVC architecture but again it really depends on the context and what you're building.