2

Is there a way to override how javascript converts complex CSS color names to rgb values when applying them to DOM elements in the document.getElementById(xxx).style object.

For example: setting document.getElementById("colorMe").style.background = "lightblue" will set the "DOMElement".style object with a background = "rgb(...)".

However, setting document.getElementById("colorMe").style.background = "blue" will set the "DOMElement".style object with a background = "blue".

I WANT the second version for all cases of color names, not just simple color names.

I would like to bypass how javascript is converting that color into an RGB value for complex color names. Is this possible?

EDIT: I Am aware there are ways to convert back and forth, I am just trying to bypass how javascript seems to be converting them "for me"... I'd like it to stay as "lightblue", and the browser seems to handle lightblue as a background color just fine.

3
  • Why not just use RGBs to begin with? Or hex codes? Commented Feb 1, 2013 at 6:44
  • as Alien said, it wouldn't make sense to go for the text, since not all colors will be represented by their name, but you can represent any color in hex or rgb() Commented Feb 1, 2013 at 6:47
  • I know I can convert back and forth, I just want to keep the color name. And I can check if the color name is valid by setting a dummy div to background: string via javascript and then check if that set was successful for any string. It works for blue, but for lightblue, javascript converts it to rgb first. I'm just wondering if this is POSSIBLE to not have it do that, not what is most reasonable. Commented Feb 1, 2013 at 6:51

1 Answer 1

2

You could use setAttribute:

element.setAttribute('style', 'background-color: lightblue'); 

To preserve the existing inline style:

var box = document.getElementById("box"), old_style = box.getAttribute('style'); box.setAttribute('style', old_style + ' background-color: lightblue;'); 

DEMO

Notice that the inline background-color is 'lightblue' and not 'rgb(173, 216, 230).'

Sign up to request clarification or add additional context in comments.

1 Comment

I appreciate that. While this is doable, I'm more of wondering an "is it possible" to override how javascript takes that complex color and actually converts it when I set it using the style.background = lightblue method. I'm having a hard time believing it's impossible since style.background = blue leaves it as "blue". If no one can find a way to override this, I will accept this as being definitely the best way around that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.