-3

Check this code please, and help me solve why i'm getting type error document.getElementById(...) is null

function Dropdown(){
    this.core = ['NIS', 'EUR', 'USD'];
    this.check = function(){
        var cho = '<select>';
        for(x in this.core){ 
            cho += '<option value="'+ this.core[x] +'">'+ this.core[x] +'</option>';
        }
        cho += '</select>';
        return cho
    };

}

var obj = new Dropdown();
document.getElementById("demo").innerHTML = obj.check();

on HTML file i have :

  <div id="demo">Check Console log</div>

Thank you for any help.

Marco Ganzo
  • 5
  • 1
  • 5
  • 5
    this code must be before html is rendered, you can put it after demo html tag, or you can use on window.load method to get that html is rendered – Álvaro Touzón Oct 13 '16 at 11:27

2 Answers2

0

You need to wait until the document is ready before interacting with it.

window.onload = function() {
    var obj = new Dropdown();
    document.getElementById("demo").innerHTML = obj.check();
};
James Monger
  • 8,229
  • 5
  • 44
  • 81
0

If you are trying to call this function when your page rendering then please put the below script before closing body tag

<script>
// self executing function here
(function() {
   // your page initialization code here
   // the DOM will be available here


function Dropdown(){
    this.core = ['NIS', 'EUR', 'USD'];
    this.check = function(){
        var cho = '<select>';
        for(x in this.core){ 
            cho += '<option value="'+ this.core[x] +'">'+ this.core[x] +'</option>';
        }
        cho += '</select>';
        return cho
    };

}
var obj = new Dropdown();
document.getElementById("demo").innerHTML = obj.check();

})();
</script>
Sunil Kumar
  • 2,655
  • 1
  • 16
  • 30