1

I have a problem, document.getElementById doesn't work. I get this error: "'null' is not an object (evaluating document.getElementById("alls").innerHTML = pixs)".

This is my code:

Javascript:

var pixs = "";
for(var ia = 1; ia <= 400 * 500; ia++) {
  var r = Math.floor(Math.random() * 257);
  var g = Math.floor(Math.random() * 257);
  var b = Math.floor(Math.random() * 257);
  pixs += "<div class='pix' style='background-color:rgb("+r+","+g+","+b+");'></div>";
}
document.getElementById("alls").innerHTML = pixs;

Body:

<div id="alls"></div>

Can anyone help me?

user3722860
  • 189
  • 1
  • 3
  • 11
  • 1
    Could you please put together a JS fiddle indicating your problem? The beauty of JS is that you can literally pass the problematic code in a working format. – christopher Aug 02 '14 at 16:54
  • Oh and while you're there, appending HTML as strings is really not a nice way to do DOM manipulation. Try to treat it more like you would XML, with elements, text nodes etc. etc. – christopher Aug 02 '14 at 16:55
  • 1
    can u please not name the class and id the same thing. – Ryan McCullagh Aug 02 '14 at 16:56
  • 3
    Chances are, the ` – Jonathan Lonowski Aug 02 '14 at 16:56

3 Answers3

3

You need to put the JavaScript behind the div. Otherwise the JavaScript will not find the div you want because it isn't existing yet.

If this is the case, you have 3 options:

  1. Move the JavaScript under the div
  2. Move the div above the javaScript
  3. Use window.onload in your JavaScript
Anton
  • 452
  • 1
  • 4
  • 16
0

Works just fine in JSFiddle, try putting the script after the div, or use something like JQuery's $(document).ready(); function.

About the code tough, it does create 200 000 nodes. enter image description here

JSFiddle link

Paradoxis
  • 3,707
  • 4
  • 24
  • 58
0

I think the problem is, maybe you call this before the DOM is loaded. You can fix this if you do this:

<html>
    <head>
        <script>
            function foo() {
                var pixs = "";
                for(var ia = 1; ia <= 400 * 500; ia++) {
                    var r = Math.floor(Math.random() * 257);
                    var g = Math.floor(Math.random() * 257);
                    var b = Math.floor(Math.random() * 257);
                    pixs += "<div class='pix' style='background-color:rgb("+r+","+g+","+b+");'></div>";
                }
                document.getElementById("alls").innerHTML = pixs;
            }
        </script>
    </head>
    <body onload="foo();">
        <!-- ... -->
        <div id="alls" class="alls"></div>
        <!-- ... -->
    </body>
</html>

That ensures, that your function is first executed, if the DOM is already loaded.

Sebi2020
  • 1,397
  • 14
  • 31