How to add multiple divs to HTML with javascript without replacing already created ones

Asked

Viewed 46 times

0

// js code, when I add twice or more only the last div is created

function Adicionar (nome) {
    
    window.onload = init;
    function init(){

        new CriarElementos();

        function CriarElementos() {
            var NovaDiv = document.createElement('div');
            var NovoH1 = document.createElement('h1');
            var TextoH1 = document.createTextNode(nome);

            NovaDiv.id = 'MeuId';
            NovaDiv.classList.add('margem');

            NovoH1.appendChild(TextoH1);
            document.getElementById('novos').appendChild(NovaDiv);
            document.getElementById('MeuId').appendChild(NovoH1);

        }

    }
}

var objeto =  new Adicionar('Pão');
var objeto2 =  new Adicionar('Leite');

1 answer

0

Basically the problem is in the structure of your code, we will only keep it as is, just put window.onload = init(), performing the function init() for when the window.
Now Voce could rewrite if code to make it simpler. First Voce removes this new because you don’t need to use classes, only functions can solve your problem. Try to do something like this:

window.onload = init(); // apos carregar a janela, inicia a funcao init() que tem toda a logia.

    function init() { // Toda sua logica deve ficar aqui dentro.
      function adicionar(nome) {
        function criarElementos() {
          var NovaDiv = document.createElement('div');
          var NovoH1 = document.createElement('h1');
          var TextoH1 = document.createTextNode(nome);

          NovaDiv.id = 'MeuId';
          NovaDiv.classList.add('margem');

          NovoH1.appendChild(TextoH1);
          document.getElementById('novos').appendChild(NovaDiv);
          document.getElementById('MeuId').appendChild(NovoH1);
        }

        criarElementos(); // chame a funcao depois de declara-la.
      }

      adicionar('Pão'); // nao precisa instanciar, apenas execute.
      adicionar('Leite');
      adicionar('Cafe');
      // .....
    }

Try to take the test. I hope I’ve helped

Browser other questions tagged

You are not signed in. Login or sign up in order to post.