0

console.log("Testing");
const p = document.createElement("p")
p.innerHTML = "This is to test the javascript extension";
const body = document.querySelector("body");
body.appendChild(p);
<!DOCTYPE html>
<html>
<head>
  <title>Testing vs code</title>
  <link rel="stylesheet" type="text/css" href="styles.css"/>
  
</head>

<body>
  <h1>Testing the vscode html preview package</h1>
  <h2>Hello</h2>
  <script type="module" src="js-prac.js"></script>
</body>
</html>

I need help, please. I posted a question earlier about this but I think I made some mistakes and made it confusing. I keep getting a "document is not defined" error every time.

is there a way I can resolve this please?

console.log("Testing");

const p = document.createElement("p")

p.innerHTML = "This is to test the javascript extension";
const body = document.querySelector("body");

body.insertBefore(p,body.childNode[-1]);
<!DOCTYPE html>
<html>
<head>
  <title>Testing vs code</title>
  <link rel="stylesheet" type="text/css" href="styles.css"/>
  
</head>

<body>
  <h1>Testing the vscode html preview package</h1>
  <h2>Hello</h2>
  <script type="module" src="js-prac.js"></script>
</body>
  • is the js code in js-prac.js? – waiaan May 26 '20 at 02:17
  • Works fine if you just change `body.childNode` to `body.children` then run it here in the page. Is that error in your browser dev tools console or a code linting error in your editor? – charlietfl May 26 '20 at 02:23
  • Do you really have said error *"document is not defined"* when you run this code from the StackSnippet in your question? That's not what most of us have (we have *"body.childNode is undefined"*, and to fix that issue, just pass `null` as the second argument of `insertBefore` if you want to insert it as last element, or even just use `appendChild()`). – Kaiido May 26 '20 at 02:49
  • @waiaan yes it is – Alisha Lawani May 26 '20 at 02:58
  • the error is: ReferenceError: document is not defined Thanks, just used the appendChild() and it makes my code look much better but that's not is not the problem apparently @Kaiido – Alisha Lawani May 26 '20 at 03:03
  • No indeed... Are you **really** clicking the "Run code snippet" button and seeing that error message? Sorry, but I strongly doubt it, that would make your browser one of the most broken browsers ever, and I can't see how it would even be able to run anything in this very page... – Kaiido May 26 '20 at 03:07
  • @Kaiido no i made the change on my text editor, not on this page – Alisha Lawani May 26 '20 at 03:12
  • ... your text editor is not a web browser and doesn't have all the assets needed to act as one. It only has a very simple js environment, but won't be able to build a DOM, and indeed won't have a `document` method. Run a web-server to test your code. – Kaiido May 26 '20 at 03:14

0 Answers0