Question

Why doesn't the following piece of code work? I'm trying to write an application that will generate a certain number of divs based on user input. When I go into the console on this application, and put in the line that says: var i = document.getElementById("foo"); It returns as null.

<div>
    <input type="number" id="foo" value="3"/>
</div>

<div>
    <script>
        var i = document.getElementById("foo");
        for (var num = 1; num <= i; num++) {
            document.write('<div id="' + i + '"> ... </div>');
        }
    </script>
</div>
Was it helpful?

Solution

Read the comments under the questions !

Also, creating proper elements is usually a good thing.

<div>
    <input type="number" id="foo" value="3"/>
</div>

<div>
    <script>
        var i = document.getElementById("foo").value;
        for (var num = 1; num <= i; num++) {
            var elem = document.createElement('div');
            elem.id  = 'elem' + num;
            elem.innerHTML = ' ... ';
            document.body.appendChild(elem)
        }
    </script>
</div>

FIDDLE

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top