Error document is not defined no undef

A pluggable and configurable linter tool for identifying and reporting on patterns in JavaScript. Maintain your code quality with ease.

Disallow the use of undeclared variables unless mentioned in /*global */ comments

Recommended

The "extends": "eslint:recommended" property in a configuration file enables this rule

This rule can help you locate potential ReferenceErrors resulting from misspellings of variable and parameter names, or accidental implicit globals (for example, from forgetting the var keyword in a for loop initializer).

Rule Details

Any reference to an undeclared variable causes a warning, unless the variable is explicitly mentioned in a /*global ...*/ comment, or specified in the globals key in the configuration file. A common use case for these is if you intentionally use globals that are defined elsewhere (e.g. in a script sourced from HTML).

Examples of incorrect code for this rule:

/*eslint no-undef: "error"*/

var foo = someFunction();
var bar = a + 1;

Examples of correct code for this rule with global declaration:

/*global someFunction, a*/
/*eslint no-undef: "error"*/

var foo = someFunction();
var bar = a + 1;

Note that this rule does not disallow assignments to read-only global variables.
See no-global-assign if you also want to disallow those assignments.

This rule also does not disallow redeclarations of global variables.
See no-redeclare if you also want to disallow those redeclarations.

Options

  • typeof set to true will warn for variables used inside typeof check (Default false).

typeof

Examples of correct code for the default { "typeof": false } option:

/*eslint no-undef: "error"*/

if (typeof UndefinedIdentifier === "undefined") {
    // do something ...
}

You can use this option if you want to prevent typeof check on a variable which has not been declared.

Examples of incorrect code for the { "typeof": true } option:

/*eslint no-undef: ["error", { "typeof": true }] */

if(typeof a === "string"){}

Examples of correct code for the { "typeof": true } option with global declaration:

/*global a*/
/*eslint no-undef: ["error", { "typeof": true }] */

if(typeof a === "string"){}

Environments

For convenience, ESLint provides shortcuts that pre-define global variables exposed by popular libraries and runtime environments. This rule supports these environments, as listed in Specifying Environments. A few examples are given below.

browser

Examples of correct code for this rule with browser environment:

/*eslint no-undef: "error"*/
/*eslint-env browser*/

setTimeout(function() {
    alert("Hello");
});

Node.js

Examples of correct code for this rule with node environment:

/*eslint no-undef: "error"*/
/*eslint-env node*/

var fs = require("fs");
module.exports = function() {
    console.log(fs);
};

When Not To Use It

If explicit declaration of global variables is not to your taste.

Compatibility

This rule provides compatibility with treatment of global variables in JSHint and JSLint.

Version

This rule was introduced in ESLint v0.0.9.

Resources

  • Rule source
  • Tests source

I’m having an error pop up in my code that I cant make dissappear. The code still works just fine but it is a bit annoying. I’m using a json array along with my html and css to list some courses as selectable buttons. This is a small class project, The buttons are populated by a given json array, and they run a small calculation when active to tell the student how many points they are expected to get during their study carreers. (I posted earlier about this and got a wonderful answer [here](https://www.reddit.com/r/learnjavascript/comments/9frg00/i_need_help_getting_an_active_button_to_return_a/) from /u/Darren1337

.HTML file:

html stuff

<div id="basic"><div>

html stuff

.JS file:

var courses, i, a = "";

courses = { "basiccourse": [{

"name": "Entrepreneuership",

"points": 3,

}, {

"name": "Engish for working life",

"points": 4,

}, {

(+50 or so others in an array)

}]

};

for (i in courses.basiccourse) {

a += "<button id='btn' value='" + courses.basiccourse[i].points + "'class='active' disabled>" + courses.basiccourse[i].name + " <br>" + courses.basiccourse[i].points + " op" + "</button>";

}

document.getElementById("basic").innerHTML = a; This is where the error occurs.

Here’s a link to the actual page, you can check it out. I am working on it so its possible the page may change or be down from time to time:

https://student.labranet.jamk.fi/~L8314/javascript/Javascript%20app/javaapp.html

https://student.labranet.jamk.fi/~L8314/javascript/Javascript%20app/courses.js

When you update Dreamweaver to the latest version 19.0, sometimes you get an error as «ERROR: ‘document’ is not defined. [no-undef]». Some of the basic JavaScript objects such as document or window are not defined. 

Environment

Dreamweaver 19.0 on all supported operating systems. 

Dreamweaver supports ECMAScript 6 syntax in Dreamweaver CC 19.0. Dreamweaver also supports linting of ECMAScript code, with ESLint defaulting as JavaScript linter.

In some instances, basic JavaScript objects are not defined. 

Add the following code to .eslintrc.js configuration file. 

"env": {
        "browser": true,
        "jquery": true
    }

Follow the steps in Workaround-2.

Dreamweaver now supports ECMAScript 6 syntax in Dreamweaver CC 19.0. Dreamweaver also supports linting of ECMAScript code, with ESLint defaulting as JavaScript linter.

The ESLint version supported in Dreamweaver CC 19.0 is 3.19. Some of the rules provided in .eslintrc.js configuration file such as for-direction and getter-return belong to the latest version of ESLint. Hence, this issue occurs. 

This issue has been fixed by updating the .eslintrc.js configuration file. Follow the steps below to use the updated .eslintrc.js configuration file. 

  1. Download the updated version of .eslintrc.js file.

    Download

    Get file

    Download and extract eslintrc.zip file to get .eslintrc.js

  2. Go to the site location and replace the existing .eslintrc.js file with the downloaded version. 

    If you have Administrator access rights, it is recommended to replace the configuration file in the installation path:

    Go to <Install path>Adobe Dreamweaver CC 2019configurationESLintrc and replace the existing .eslintrc.js file with the downloaded version. 

    Note:

    • The ECMAScript Version settings defined in site setup dialog has precedence over the .eslintrc.js file used in site root. 
    • If you do not have ESLint configuration files in the site, Dreamweaver searches for the configuration files in all locations leading up to the root directory.

    For more information on configuration file cascading and hierarchy, see ESLint site. 

I’m building a React app, with create-react-app.

I got the following error when running eslint: 8:3 error ‘document’ is not defined no-undef.

Here are the following .jsx file and my eslint configuration. My app runs without error, but I got this eslint error in 2 files.

index.jsx :

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';

ReactDOM.render(
  <App />,
  document.getElementById('root'),
);

eslintrc.js :

module.exports = {
  "extends": "airbnb",
  "plugins": [
      "react",
      "jsx-a11y",
      "import"
  ],
  "env": {
    "jest": true
  }
};

How can I fix this ? For the moment I will simply ignore both files … but I’d rather find a long term solution.


Add "browser": true your env to include global variables (like document, window, etc.)

See the ESLint environment documentation for more information.

The solutions mentioned in this article will help you to fix the error “ReferenceError: document is not defined”. In some case you may encounter it in Node.js or with Next.js. Follow these instructions to fix it.

Find more about JS Type of Errors

What causes the error “ReferenceError: document is not defined”?

The error “ReferenceError: document is not defined” in Node.js occurs when the document object you are calling is not defined in your code.

The document object in JavaScript represents the entire HTML document. 

When the HTML document is loaded in the browser, it becomes a document object. The document object is a property of the window object.

You can’t find the window and document objects when your code is generated on the server side(using the Next JS). So it will cause the error.

The error may appear as below:

ReferenceError: document is not defined
try running it on browser not on node.js

One more case you can encounter is a misspelled document object. You must write all in lowercase, the implicit rule in object naming in javascript.

Solution 1: Using the dynamic rendering

If you use the Next JS framework for your website and rendering on the server side, you should use dynamic rendering to generate what you want, like so:

import dynamic from 'next/dynamic'
const DynamicComponentWithNoSSR = dynamic(() => import('../components/List'), {
  ssr: false
})

Then insert the code you want to execute on the client side. Below is the code using the useEffects of React Hook:

const DynamicComponentWithNoSSR = <>Some JSX</>

export default function App(){
[a,setA] = useState();
useEffect(() => {
    setA(<DynamicComponentWithNoSSR/>)
  });

return (<>{a}<>)
}

Solution 2: Check if the document object is defined

More straightforwardly, you can check if the document object is defined or not:

if (typeof document === 'undefined') {
    // during server evaluation
} 

else {
    // during client's browser evaluation
}

If only you need to run the browser of the client. Just do the following, the error will be fixed without resorting to dynamic rendering:

var body = null;

if (typeof document !== 'undefined') {
    // will run in client's browser only
    body = document.getElementsByTagName("body")[0];
}

Another thing that can fix the “ReferenceError: document is not defined” error is that you have to put the script tag at the end of the body tag. Now call the document object. It was defined before rendering DOM:

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>

<body>
    <div id="divid">Next</div>
    <script type="text/javascript" src="script.js"></script>
</body>

</html>

Summary

To avoid getting the “ReferenceError: document is not defined” error, you must ensure the document object is written correctly. Besides, you must decide whether you are on the browser or the server. Calling the document object on the server will cause an error in your code, so be careful when using this object.

Maybe you are interested in similar errors:

  • ReferenceError: document is not defined in JavaScript
  • “forEach is not a function”
  • Uncaught SyntaxError: Unexpected token
  • Cannot read properties of undefined

Tom

My name is Tom Joseph, and I work as a software engineer. I enjoy programming and passing on my experience. C, C++, JAVA, and Python are my strong programming languages that I can share with everyone. In addition, I have also developed projects using Javascript, html, css.

Job: Developer
Name of the university: UTC
Programming Languages: C, C++, Javascript, JAVA, python, html, css

Старый

01.02.2020, 13:54

Новичок на форуме

Отправить личное сообщение для eternal_blue

Посмотреть профиль

Найти все сообщения от eternal_blue

 

Регистрация: 01.02.2020

Сообщений: 4

ошибка ‘document’ is not defined [no-undef]

Сделал часы на js, получил две ошибки, ‘document’ is not defined [no-undef] и ‘setinterval’ is not defined [no-undef]. Написал краткий скрипт, проверить. Все равно вылазит, что делать? Работаю в brackets.

function dd() {
    var d = 3;
    document.getElementById('clock').innerHTML = d;
}
setInterval(dd(), 1000);

Ответить с цитированием

Старый

01.02.2020, 14:07

Аватар для рони

Профессор

Отправить личное сообщение для рони

Посмотреть профиль

Найти все сообщения от рони

 

Регистрация: 27.05.2010

Сообщений: 32,656

eternal_blue,

<div id="clock"></div>
<script>
var d = 3;
function dd() {
    document.getElementById('clock').innerHTML = d++;
}
setInterval(dd, 1000);
</script>
</body>

Ответить с цитированием

Старый

01.02.2020, 14:10

Новичок на форуме

Отправить личное сообщение для eternal_blue

Посмотреть профиль

Найти все сообщения от eternal_blue

 

Регистрация: 01.02.2020

Сообщений: 4

Все те же ошибки. Может проблема в среде разработки?

Ответить с цитированием

Старый

01.02.2020, 14:13

Аватар для рони

Профессор

Отправить личное сообщение для рони

Посмотреть профиль

Найти все сообщения от рони

 

Регистрация: 27.05.2010

Сообщений: 32,656

eternal_blue,
возможно у вас нет элемента id=»clock» на момент запуска скрипта.

Ответить с цитированием

Старый

01.02.2020, 14:21

Новичок на форуме

Отправить личное сообщение для eternal_blue

Посмотреть профиль

Найти все сообщения от eternal_blue

 

Регистрация: 01.02.2020

Сообщений: 4

Ну прочитал я статью. Можете просто объяснить, как сделать чтобы работало?

Ответить с цитированием

Старый

01.02.2020, 14:22

Новичок на форуме

Отправить личное сообщение для eternal_blue

Посмотреть профиль

Найти все сообщения от eternal_blue

 

Регистрация: 01.02.2020

Сообщений: 4

Есть, я попробовал в песочнице запустить это, не работает

Ответить с цитированием

Старый

01.02.2020, 14:44

Аватар для рони

Профессор

Отправить личное сообщение для рони

Посмотреть профиль

Найти все сообщения от рони

 

Регистрация: 27.05.2010

Сообщений: 32,656

eternal_blue,
здесь работает?

Ответить с цитированием

Старый

01.02.2020, 14:45

Аватар для рони

Профессор

Отправить личное сообщение для рони

Посмотреть профиль

Найти все сообщения от рони

 

Регистрация: 27.05.2010

Сообщений: 32,656

eternal_blue,
ссылку на песочницу можно увидеть?

Ответить с цитированием

Depending on your environment and setup, you can run into an error when you try to reference the document object.

Specifically, the error will look like this:

	ReferenceError: document is not defined

In this post, we’ll look at the most common reasons for this error and how to best avoid getting them.

On Node

The most common reason for this error is because you’re using Node.

That is to say, you are trying to access the document object on the server, but the server does not have access to the document object because it lives on the browser.

Node is a server-side runtime so if you’re on Node, you cannot reference the document object, which is an in-memory representation of the Document Object Model.

That also includes when you’re doing server-side rendered applications, which can sometimes have universal code that can run on both the server and the browser.

On Browser

The most common reason for getting the reference error while on the browser is when you try to access the document object too early.

The best way to resolve this is to just move your code to the bottom of the page so that the document will be ready by the time your code references it.

	<html>
    <head>
        <title>HTML page</title>
    </head>
    <body>
        <!-- HTML here -->

        <!-- your script here -->
        <script type="module" src="index.js"></script>
    </body>
</html>

If you want to check for the existence of the document object, you can use the following code:

	if (typeof document !== "undefined") {
    // document exists
} else {
    // document does not exist
}

Once you can confirm that the document is available, you can then reference the document object without getting reference errors:

	if (typeof document !== "undefined") {
    document.getElementById("my-element");
}

Conclusion

In this post, we looked at the most common reasons that causes the document reference error in JavaScript.

The main culprits are using server-side JavaScript like Node, or calling your script before the document is ready.

Hopefully, this was helpful to you. Thanks for reading!

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

  • Support Us

  • Join

  • Share

  • Tweet

  • Share

Give feedback on this page!

Понравилась статья? Поделить с друзьями:
  • Error docker exporter does not currently support exporting manifest lists
  • Error do not access object prototype method hasownproperty from target object no prototype builtins
  • Error dmg image is corrupted
  • Error dlopen failed
  • Error dll prototype2engine dll does not contain required exports что делать