skip to Main Content

Why Array gives null outside script onclick event in htm5? The others variables works correctly.

<!DOCTYPE html>
<html>
<head>
  <title>Array</title>
  <script>
    var list = new Array("andrea", "matteo", "marco");
    var x = "andrea";
  </script>
</head>
<body>
  <input type="button" value="click" onclick="alert(list[0]);">
</body>
</html>

2

Answers


  1. It’s because list is not in scope of your onclick attribute. You can prefix it with window to target it directly:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Array</title>
      <script>
        var list = new Array("andrea", "matteo", "marco");
        var x = "andrea";
      </script>
    </head>
    <body>
      <input type="button" value="click" onclick="alert(window.list[0]);">
    </body>
    </html>

    Better still, you should avoid using onX attributes wherever possible. Use unobtrusive event handlers bound in JS. You can also use this method to avoid using global variables:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Array</title>
      <script>
        window.addEventListener('load', () => {
          const list = ["andrea", "matteo", "marco"];
          
          document.querySelector('input').addEventListener('click', e => {
            console.log(list[0]);
          }); 
        })
      </script>
    </head>
    <body>
      <input type="button" value="click">
    </body>
    </html>
    Login or Signup to reply.
  2. You should wait for the DOM to be fully loaded before trying to access the list array. You can use the DOMContentLoaded event for this purpose.

    Here’s an updated version of your code:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Array</title>
      <script>
        document.addEventListener("DOMContentLoaded", function() {
          var list = new Array("andrea", "matteo", "marco");
          var x = "andrea";
    
          document.getElementById("myButton").onclick = function() {
            alert(list[0]);
          };
        });
      </script>
    </head>
    <body>
      <input type="button" value="click" id="myButton">
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search