-1

The code below, produces the same annoying error. It will return the button element in the first pass of the loop but it only returns null thereafter. Any ideas?

 <script>
    function  Check_Submission()
    {var Entry = [];
        for(var i = 0; i < 14; i++)
        {
            for(var j = 0; j < 10; j++)
            {
                 Entry[i] = document.getElementById('Add');
                document.write(Entry + '<br>');
            }
        }
    }
    </script>

    <button id = 'Add' onclick = "Check_Submission()" >Click me.</button>
Timigen
  • 997
  • 17
  • 32
Gaven
  • 643
  • 2
  • 7
  • 13
  • 1
    What are you attempting to do? You are looping through this 140 times, adding the same one button element to your `Entry` array. – Sam May 09 '14 at 17:58
  • In my main code there are many edit boxes with ID Input_i_j so I retrieve their contents dynamically – Gaven May 09 '14 at 18:00
  • [why is document.write considered a bad practice?](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – epascarello May 09 '14 at 18:01

4 Answers4

3

When you do document.write() to an already loaded document, it clears the current document and starts writing a new empty document.

So, as soon as you call the first document.write() in your loop, it clears the current document and then document.getElementById('Add') will no longer find the former content.


Probably what you should do is to use DOM insertion methods such as .appendChild() or .insertBefore() to add new content to an existing loaded page.

jfriend00
  • 580,699
  • 78
  • 809
  • 825
3

You can not use document.write after the page load. When you do that it wipes away the page content.

  • First loop it finds the element
  • You write to the page, it removes the button
  • other iterations can not find it since it was removed.

You need to use DOM methods to add new content or use the console for debugging.

epascarello
  • 185,306
  • 18
  • 175
  • 214
0

It seems to me like the first time you run your for loop, you use document.write. That will clear everything, so the document.getElementById('Add') will return nothing. what you really want to do is something like 'appendChild' or modifying the innerHTML of the element.

deweyredman
  • 1,400
  • 1
  • 8
  • 12
0

document.write will clear everything each time it is executed. Try writing,

document.getElementById('divid').innerHTML+=Entry+'<br>';

<div id='divid'></div>
Funk Forty Niner
  • 73,764
  • 15
  • 63
  • 131
Saumil
  • 2,399
  • 4
  • 25
  • 53