Create divs every click on the specified size and color button

Asked

Viewed 126 times

0

Good night!! I am hitting myself in this challenge of creating a div with the parameters passed in each click that is given in the button, I made this code but it seems that it did not work, where I may have missed?

<body>
<input type="button" value="clicar" id="btn" onclick="clicar()">

<script>

function clicar(){
    var divElement = document.createElement("div")
    divElement.setAttribute('id', 'box')
    var boxElement = document.getElementById("box")
    divElement.appendChild(boxElement)

    boxElement.style.width = 100;
    boxElement.style.height = 100;
    boxElement.style.backgroundColor = "#f00";

}

</script>

1 answer

1

Mario,

There are some incorrect points:

  • You set the ID as a box, but the idea of the ID is that it is unique, each element must have your ID, that way you break this idea
  • You create the element, search for it in the DOM, but it has not yet been added to the same... Then try to add the created element on itself with appendchild

To fix, you must create the element and add it to some other, it can even be another div or even in the body itself.

See how this can be implemented:

<input type="button" value="clicar" id="btn" onclick="clicar()">
<!--DIV criada apenas para armazenar as demais divs-->
<div id="mae"></div>

<script>
  //A variável de ID ficou fora das funções para manter o estado...
  let id = 0;

  //Retorna o próximo ID válido para a DIV que será criada
  function getNextId() {
    return ++id;
  }

  //Sua função, chamada no click do botão
  function clicar(){
      //Pego o ID
      let id = getNextId();
      //Crio a DIV
      let divElement = document.createElement("div");
      //Pego a DIV onde a nova DIV será criada, sempre na DIV mãe
      let divMae = document.getElementById("mae");

      //A ideia do ID é que ele seja um elemento único, ou seja, não se repita
      divElement.setAttribute('id', 'box' + id.toString());

      //CSS
      divElement.style.width = "100%";
      divElement.style.height = "50px";

      //Essa parte é mais para deixar claro que outras divs estão sendo criadas, criando um degrade
      divElement.style.backgroundColor = "#f0" + id.toString();

      //Adiciono a nova DIV na DIV mãe
      //Aqui poderia ser por exemplo document.body.appendChild, adicionando assim o elemento criado diretamente no body
      divMae.appendChild(divElement);
  }
</script>

Note that I created a variable to be the ID, always incrementing it and thus preventing the repetition of the ID. In this example, I created a 'mother' DIV, which is where new Divs will be added.

Browser other questions tagged

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