Changing Background and Text Color of HTML ElementsQuestion: Can I programmatically change the color of an HTML element from JavaScript?
Answer: Yes, it's possible to set or read the background and text colors of individual HTML elements
such as
Modern browsers accept 'red' , 'blue' , 'purple' , 'navy' )
rgb(Rvalue,Gvalue,Bvalue) - for example, rgb(255,0,0) for red
#RRGGBB (e.g. '#FF0000' for red, '#0000FF' for blue, '#FFFFFF' for white)
The following demo allows you to change the colors for the highlighted Element 1 Change the background color to any of the following: maroon peru red rgb(255,255,0) lime aqua #BBBBDD teal navy purple Element 2 Change the foreground color to any of the following: maroon peru red rgb(255,255,0) lime aqua #BBBBDD teal navy purple This demo uses the functions function setBgColorById(id,sColor) { var elem; if (document.getElementById) { if (elem=document.getElementById(id)) { if (elem.style) { elem.style.backgroundColor=sColor; return 1; // success } } } return 0; // failure } function setColorById(id,sColor) { var elem; if (document.getElementById) { if (elem=document.getElementById(id)) { if (elem.style) { elem.style.color=sColor; return 1; // success } } } return 0; // failure }To read the current background color of an HTML element, given the element ID, you can getBgColorById(id) :
function getBgColorById(id) { var elem; if (document.getElementById) { if (elem=document.getElementById(id)) { if (elem.style) return ''+elem.style.backgroundColor; } } return 'undefined'; }Interestingly, the returned color format may depend on the browser. For example, Firefox returns 'rgb(187, 187, 221)' '#BBBBDD' .
Internet Explorer does it the other way round: IE returns '#bbbbdd'
even if the color was set to 'rgb(187, 187, 221)' .
See also:
|
|
Copyright © 1999-2012, JavaScripter.net.