Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
Javascrpt style give me problems

VS code gives me an error:

Uncaught TypeError: Cannot read properties of undefined (reading 'style') at HTMLButtonElement.acc

function acc() {

  if (button.style.display == 'none') {
    button.style.display = 'block';
    var button = document.createElement('button');
    var div = document.createElement('div');
    var img = document.createElement('img');
    var h4 = document.createElement('h4');

    div.appendChild(button);
    div.appendChild(img);
    div.appendChild(h4);

    h4.style.color = 'red';
    h4 = 'Account';

    button.innerHTML = h4;
    div.classList.add('achi');

    document.getElementById('achi').appendChild(div);

  } else {
    button.style.display = 'none';
  }

}

let accBtn = document.getElementById('acc-btn');
accBtn.addEventListener('click', acc);

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. You don't need an if check for the styles of an element you just created. You define the styles of your brand new element.
  2. You define a variable named h4 and set it to point to an element, then redefine it later on to equal a string. Weird. Don't do that.
  3. You can't access button before it's been defined. It is undefined up until that point.
  4. The <h4> tag is empty. Do you want that?
  5. Don't use innerHTML to just set text content. Use textContent or innerText instead (innerText keeps the newlines).

Refactored:

const accBtn = document.getElementById('acc-btn');

function acc() {
    const div = document.createElement('div');
    div.classList.add('achi');

    const button = document.createElement('button');
    button.style.display = 'block';
    button.textContent = 'Account'

    const img = document.createElement('img');

    const h4 = document.createElement('h4');
    h4.style.color = 'red';

    div.appendChild(button);
    div.appendChild(img);
    div.appendChild(h4);

    document.getElementById('achi').appendChild(div);
}

accBtn.addEventListener('click', acc);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda