Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

317
Vistas
onClick function does not work (not changing color of the string)

I am trying to make a dynamic function onClick which will change the color of the string, but color won't change, same function works if I call 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'
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are using wrong the strict equality (===) and misses a curly brace.

Your code should be:

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'
    }
}

Here is a fiddle https://jsfiddle.net/tghcrzum/

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda