JavaScript: Add Div at the push of a button - TypeError: Can not set property 'innerHTML' of null

0

What's wrong with my code. I already tested on Codepen and it works normally. Even the order of the elements are the same there, but in my WordPress does not want to work. Note that here also works. Error displayed - > TypeError: Can not set property 'innerHTML' of null

<label for="file">Envie sua receita.</label>
   <input type="file" id="file" name="file" multiple>
   <div id="div1"></div>
<a href="javascript:addCampo();"><i id="addFile" class="glyphicon glyphicon-plus">+</i></a>
<script>
var i = 1;
function addCampo(){ 
  var idDiv = 'div'+i;
  document.getElementById(idDiv).innerHTML = '<input type="file" id="file'+i+'" name="file'+i+'" multiple>';
   i++;
}
</script>

It's just the same. I just made a Ctrl + C & Ctrl + V .

    
asked by anonymous 06.03.2018 / 14:20

1 answer

0

The problem is that at no point is the next div being accessed. An example how to resolve this is:

<html>
<div id="principal">
<label for="file">Envie sua receita.</label>
   <input type="file" id="file" name="file" multiple>
   <div id="div1"></div>
</div>
<a href="javascript:addCampo();"><i id="addFile" class="glyphicon glyphicon-plus">+</i></a>
</html>
<script>
   var i = 1;
   function addCampo(){
      var idDiv = 'div'+i;
      document.getElementById(idDiv).innerHTML = '<input type="file" id="file'+i+'" name="file'+i+'" multiple>'; i++;
      document.getElementById('principal').innerHTML += '<div id="div'+i+'">
      </div>';
   }
</script>
    
06.03.2018 / 15:07