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

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

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