Frage

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>
War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top