Changing Background and Text Color of HTML Elements
Answer: Yes, it's possible to set or read the background and text colors of individual HTML elements such as
, and others. To change the background color for a specific HTML element on the page, set the property
to the desired color value. Similarly, to change the text color (or foreground color), use the property
Modern browsers accept
values in any of these formats:
The following demo allows you to change the colors for the highlighted
elements (Element 1 and Element 2). Click on the hyperlink red, navy, purple, etc.
elements will be programmatically changed to the color you clicked.
This demo uses the functions
for changing the background and text color of any given HTML element, as specified by the input arguments
(the element ID) and
(the desired color):
To read the current background color of an HTML element, given the element ID, you can
Interestingly, the returned color format may depend on the browser. For example, Firefox returns
even when the color was set to
. Internet Explorer does it the other way round: IE returns
even if the color was set to
. You can always use the Hex-to-RGB and RGB-to-Hex converters to switch between these two equivalent color formats.