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

311
Visualizações
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 Respostas
Responde à pergunta

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