I am new to coding and am trying to build a very basic website with html, css and js.
When referring to code in the html file from js, I encounter an issue.
My HTML file contains the following code:
<!DOCTYPE html>
<html>
<head>
<title>random stuff</title>
<script src="Mgen.js"> </script>
</head>
<body>
<p id="quote"> quote </p>
</body>
</html>
Mgen.js in src="Mgen,js" is a hyperlink that links to the correct js file, which file is stored in the same folder as the HTML file.
In Mgen.js I have included the following code to test the connection between the files:
let quote = document.getElementById('quote')
console.log(quote)
This gives the following error message:
Uncaught ReferenceError ReferenceError: document is not defined
at <anonymous> (undefined:1:13)
at Module._compile (undefined:1105:14)
at Module._extensions..js (undefined:1159:10)
at Module.load (undefined:981:32)
at Module._load (undefined:822:12)
at executeUserEntryPoint (undefined:77:12)
at <anonymous> (undefined:17:47)
I have been stuck here for hours. I have installed node.js and enabled and disabled auto-attach. I have also tried checking the code through a browser, here too no elements of the js file show (I tried this with different js code that should be shown in a browser if functional).
I understand this is a very basic question, yet I'd be very grateful for any solution.
CodePudding user response:
it seems like your JavaScript is running on node. In that case, your JavaScript would run on the server (and not in the client - your browser). Only when JavaScript runs in the browser, there is the document.
Try one thing: Shut down node and just open the plain HTML file in your browser.
That should work in that regard, that document
should now be defined, but you might encounter another error: Your quote p
will not be defined, because you load the JavaScript and execute it before you define the paragraph. In that case: Place the script tag before the closing body tag.
CodePudding user response:
The imported JavaScript file is loading before the HTML DOM is ready. Hence document elements will not be found. then you can use it as text/javascript in the script tag
Use an example here.
<script type="text/javascript">
let quote = document.getElementById('quote')
console.log("quote---",quote)
</script>