0

I have a HTML code below

    var div1=document.querySelector("#div");
    function p1(){ div1.style.display="none";alert("p1");}
    <script src="o.js"></script>
    <button onclick="p1();">p1</button>
    <div id="div" style="display:block;">div1</div>

It is not working at all because global var div1 is not updated I guess.

if I put var div1 into function p1, it works.

However, I want to create a lot of global variables, so I don't need to repeat a lot in every other function.

JMP
  • 4,417
  • 17
  • 30
  • 41
Jkil
  • 19
  • 7
  • `var div1=document.getElementById("div");` is executed before `
    div1
    ` is in the DOM - you can move that line of code inside the function p1 and all will be good
    – Bravo Nov 16 '20 at 09:35
  • Your code works fine as long you make sure it's executed after the DOM is loaded. https://jsfiddle.net/h8od9mg1/ – Mark Baijens Nov 16 '20 at 09:40

1 Answers1

2

Place your script tag at the end of the body tag. Your file is executed in a chronological order, therefore, your script cannot find any element with the id of "div". So place it like this -

<button onclick="p1();">p1</button>
<div id="div" style="display:block;">div1</div>
<script src="o.js"></script>