Estoy tratando de hacer una función dinámica onClick que cambiará el color de la cadena, pero el color no cambiará, la misma función funciona si llamo a consol.log
const heading = document.getElementById('Hello') function addStyleTo(node, text, color, fontSize) { node.textContent = text node.style.color = color node.style.textAlign = 'center' node.style.backgroundColor = 'black' node.style.padding = '2rem' node.style.fontSize = fontSize } setTimeout(() => { addStyleTo(heading, 'Hello', 'red', '3rem') }, 1000); heading.onclick = () => { if (heading.style.color === 'red') { heading.style.color === 'pink' } else { heading.style.color === 'red' }Está usando incorrectamente la igualdad estricta (===) y pierde una llave.
Su código debe ser:
const heading = document.getElementById('Hello') function addStyleTo(node, text, color, fontSize) { node.textContent = text node.style.color = color node.style.textAlign = 'center' node.style.backgroundColor = 'black' node.style.padding = '2rem' node.style.fontSize = fontSize } setTimeout(() => { addStyleTo(heading, 'Hello', 'red', '3rem') }, 1000); heading.onclick = () => { if (heading.style.color == 'red') { heading.style.color = 'pink' } else { heading.style.color = 'red' } }Aquí hay un violín https://jsfiddle.net/tghcrzum/