0

I wrote the following HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>Test</title>
        <script type = "text/javascript" src =
        "../js/test.js"></script>
    </head>
    <body>
        <p><input type = "button" value = "Click";></input></p>
    </body>
</html>

and the corresponding JavaScript file test.js

var inputs = document.getElementsByTagName("input");
console.log(inputs.length);

and the value shown is 0. Can anyone explain?

Addem
  • 3,118
  • 3
  • 24
  • 47
  • 3
    you are trying to get the element before it's loading to dom – Pranav C Balan Feb 11 '17 at 08:36
  • Is that the whole JavaScript file? Also `` is self-closing. The `` is not necessary. – putvande Feb 11 '17 at 08:37
  • @putvande My understanding--correct me if I'm wrong--is that even with tags that are self-closing, it's good practice to close them somehow. Like it's better to write `
    ` even though `
    ` would work. This is just what I've heard.
    – Addem Feb 11 '17 at 17:58

1 Answers1

1

You are trying to get the element before it's loading to DOM, to execute after elements are loaded move the script tag after the elements or add it within the onload event handler.

window.onload = function(){
   var inputs = document.getElementsByTagName("input");
   console.log(inputs.length);
}
Pranav C Balan
  • 106,305
  • 21
  • 136
  • 157