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

198
Views
How can i make JavaScript If Style Color work?

I have a simple if condition that checks the color of a element...

function changeBackgroundColor(element) {
          if (element.target.style.color == "#1abc9c"){
            // Do nothing
          } 
          else { // Whatever }

But it is not working. If i use common names like "Yellow, green, etc" it works. Any tips?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

style.color gives the direct color name or rgb value. It does not gives hex code. So for your case, you first need to change your hex code to rgb, then compare it with style.color So what you can do you can create a utility function

function getRgbFromHex(hexColorCode){
  const hexCode =  hexColorCode.startsWith('#') ? hexColorCode.substr(1) : hexColorCode;
  const hexR = hexCode.substring(0,2);
  const hexG = hexCode.substring(2,4);
  const hexB = hexCode.substring(4,6);
  
  return `rgb(${parseInt(hexR, 16)},${parseInt(hexG, 16)},${parseInt(hexB, 16)})`
  }

and then you can change your if condition to UPDATE Removing spaces from style.color

if (element.target.style.color.replace(/\s/g,'') == getRgbFromHex("#1abc9c"))
about 4 years ago · Juan Pablo Isaza Report

0

document.getElementById('main').style.color returns a RGB value, not a HEX value.

Example:

if (document.getElementById('main').style.color == 'rgb(26, 188, 156)') {
    console.log("Colour is set")
} else {
    
}
<div id="main"  style="color: #1abc9c">
    Hello, world!
</div>

<script src="test.js"></script>
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!