Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!