How to create a button that when clicked creates a new element with Javascript?

Asked

Viewed 167 times

0

I’m trying to fix it, but I’m struggling, I don’t know what I’m doing wrong.

Create a button that when clicked creates a new element on screen with the shape of a red square with 100px of height and width. Whenever the button is clicked a new square should appear on the screen.

<div id="app">

  <button class="botao">Adicionar</button>
  <div class="box">
  </div>

</div>
<script>
  var btnElement = document.querySelector('button.botao').addEventListener("click", criarQuadrado);
  var newQuadrado = document.querySelector('div.box');
  newQuadrado.style.backgroundColor = red;
  newQuadrado.style.width = 100;
  newQuadrado.style.height = 100;


  function criarQuadrado() {
    btnElement.createElement(newQuadrado);



  }
</script>

screenshot do código
Click to view the code screenshot

  • 1

    In your code you only have red (who in this case is acting as a identifier which, as it is not defined, will launch a ReferenceError variable not defined). You must use a string, that is to say, "red" (which is, in fact, a "text", and not an identifier).

1 answer

1

I made some important changes to your code.

  1. First thing was to remove the div box from the screen, it should appear only when the user clicks the button.
  2. Note that in the function creatureWill created the element and stored the created element in a variable, repairs tbm that this element does not yet exist in the DOM.
  3. When I put the color in the div, I need to assign a string to that value, in your case vc was assigning a global variable (red), notice that red is different from 'red', this is very important.
  4. When you are going to assign a height(height) or width(width), you need to pass a string because we need to know which unit of measure, so I passed '100px' and not 100 as vc was passing.
  5. And lastly, instead of using the createelement, I used the appendchild passing as a parameter the div that we created dynamically after the click...

I hope you helped, any questions can send me an email that we can talk more.

[email protected]

<body>
  <div id="app">
    <button class="botao">Adicionar</button>
  </div>
  <script>
    var btnElement = document.querySelector('button.botao');
    btnElement.addEventListener("click", criarQuadrado);

    function criarQuadrado() {
      var newDiv = document.createElement('div');
      newDiv.style.backgroundColor = 'red';
      newDiv.style.width = '100px';
      newDiv.style.height = '100px';
      document.querySelector('#app').appendChild(newDiv)
    }
  </script>
</body>

  • Thank you very much! It cleared up a lot for me!

  • any doubt can call me in the email, let’s codar!

Browser other questions tagged

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