Search code examples
javascriptreferenceerror

I do not understand why I get this error?


Why do I always get an error on myfunc() is not defined?

<button onclick = "myfunc();">submit</button>
<script src="script.js">
   function myfunc(){
     let person = {
       name: document.getElementById("demo");
     }
     alert(person.name);
   }
</script>



Solution

  • Its a basic fact, your script gets ignored if that script tag has an src attribute

    enter image description here

    Solution: make a second script tag with no src attribute.

    <button onclick="myfunc();">submit</button>
    <script src="script.js"></script>
    <script>
       function myfunc(){
         let person = {
           name: document.getElementById("demo")
         }
         alert("it works");
       }
    </script>