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);
if check for the styles of an element you just created. You define the styles of your brand new element.h4 and set it to point to an element, then redefine it later on to equal a string. Weird. Don't do that.button before it's been defined. It is undefined up until that point.<h4> tag is empty. Do you want that?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);