Reputation: 81
If I have a variable in the <script>
tags of an HTML document; lets call it example
.
How can I access example
in my JavaScript file?
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/example.css">
<link rel="icon" href="https://www.example.com/icon.png">
<title>Exsample</title>
</head>
<body>
<script>
var example = "example"
</script>
</body>
Upvotes: 1
Views: 2991
Reputation: 3082
Nowadays in 2023, using ES2022, you can access your JS variable in HTML document from an external JavaScript file as following :
//in your test.js file
const myVar = `John DOE`
export default {myVar}
then in your HTML file
<script type="module">
import myVar from 'test.js';
console.log(`myVar=` + myVar)
</script>
the console returns the following result:
▶ {myVar: 'John DOE'}
Upvotes: 1
Reputation: 944568
Scripts loaded with <script>
elements (type=module
aside) all share the same JS environment.
A variable created in the global scope by one will be available in all the others.
The only other proviso is that you can't access a variable before you create it.
<script>
var example = 1;
</script>
<script>
console.log(example);
</script>
There is no difference between scripts where the script is loaded via src
and those with the script provided inline.
Upvotes: 4
Reputation: 14798
You should be able to access it through window.example
. If example
is declared in a function, you won't be able to access it. Your external script must also appear after the variable declaration (or you can use the defer
option on the script):
console.log(window.example);
<script>var example = 'example';</script>
Upvotes: 1