We have a function:

function createMatrix() { var matrix = document.getElementById('matrix'); var n = 20 * 20; for (var i = 0; i < n; i++) { var div = document.createElement('div'); div.setAttribute('id', 'div_' + i); div.className = 'cell'; matrix.appendChild(div); } r = (randomcell(0,399)); small_div = document.getElementById('div_' + r); small_div.className = 'black'; } 

Outside of this function, I write for example: small_div.setAttribute('id', 'div_13'); Just to check if it works. Writes "small_div is not defined". Why? It seems that without var the declaration goes to the function? I am new to javascript. Help, please, with features when working with objects in Javascript. Thank you in advance.

    1 answer 1

    Declare small_div as global (outside the function) before the function starts. Those. something like this:

     var small_div = false; createMatrix(); if (!!small_div) alert(small_div.id); 

    General infa: do not confuse, the ad always comes with a var . Simply using var inside a function declares it as local.

     function ga1() { var a = 15; } function ga2() { a = 13; } ga2(); // a is not defined var a = 11; alert(a); // 11 ga1(); alert(a); // 11, ибо а - локальная ga2(); alert(a); // 13 
    • but isn't it that we are not announcing a variable of type bool? If you do as you said, then on the line "small_div.setAttribute ('id', 'div_13');" writes "small_div.setAttribute is not a function" - Jet
    • JS is not typed) !! small_div gives "not (not (small_div))", i.e. "is not false / empty", and the object is not empty. in general, js quite calmly does this: <pre> var a = false; // bool a + = 5; // int a = 'lol _' + a; // string a = {b: a}; // object </ pre> Next: check ( alert(document.getElementById('div_13')) ) that div with id = div_13 exists. If not, try setting the ID after matrix.appendChild(div); - Sh4dow 6:26 pm
    • Thank you Sh4dow. My mistake was that I did not know that at first everything would be executed after the entry point, AND ONLY AFTER FUNCTION window.onload. Consequently, the matrix and small_div object was created in window.onload. And I wanted to use it no longer in this function. In general, an ordinary Lamer blunted ...) - Jet