Create stylized HTML element using Javascript

Asked

Viewed 174 times

0

I’m trying to create a red block on the page using HTML, but for some reason the code doesn’t work. The browser console does not return any error and nothing happens on screen. The program is like this:

function criar(){
    let box = document.querySelector('.box');
    box.style.width = 100;
    box.style.height = 100;
    box.style.background = '#f00';
    box.style.color = '#f00';
}
<button onclick="criar()">Criar Quadrado</button>
   
<div class="box">

</div>

Does anyone know how to solve?

2 answers

2


Missing vc define width and Heigh measurement unit

function criar(){
    let box = document.querySelector('.box');
    box.style.width = '100px';
    box.style.height = '100px';
    box.style.background = '#f00';
    box.style.color = '#f00';
}
<button onclick="criar()">Criar Quadrado</button>
   
<div class="box">

</div>

  • Oh yes, of course. I saw a tutorial where the unit was not used. Thank you!.

  • 1

    Glad to have helped If possible... mark the answer as valid... help me, and help the community

0

Initially your problem is the lack of unit definition in the measures of width and height, moreover, if you really want to create elements and not just stylize some existing previously in the DOM, you can do it by creating it via javascript and then placing it anywhere in the DOM as you like in this example:

function criarQuadrado(cor = '#000') {
  const quadrado = document.createElement('div');
  quadrado.style.width = '64px';
  quadrado.style.height = '64px';
  quadrado.style.margin = '8px';
  quadrado.style.backgroundColor = cor;
  document.querySelector('#resultado').appendChild(quadrado);
}
#resultado {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  justify-content: flex-start;
  flex-wrap: wrap;

  max-width: 512px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <button onClick="criarQuadrado('blue')">Criar Quadrado Azul</button>
  <button onClick="criarQuadrado('red')">Criar Quadrado Vermelho</button>
  <button onClick="criarQuadrado('green')">Criar Quadrado Verde</button>
  <div id="resultado"></div>
</body>

</html>

Browser other questions tagged

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