Your js example is not valid and should not do anything ...

You need to set the style on each span element;

Copyvar ea = document.getElementsByClassName('name');
for(var i = 0; i < ea.length; i++)
        ea[i].style.backgroundColor = "yellow";
Answer from Alex K. on Stack Overflow
🌐
Medium
colton-shawn-oconnor.medium.com › changing-text-color-based-on-the-background-in-javascript-947bf9bc136b
Changing Text Color based on the Background in JavaScript | by Colton Shawn O'Connor | Medium
April 2, 2021 - Now you are dynamically changing your text color! This is a great way to add some more color to your app without risking readability. If you want to check out the apps where I implemented this you can find my JavaScript implementation here, and my React Native Implementation here.
Discussions

Javascript code for text color and background color
Hi Everyone, Does anyone have a javascript code to let me change text and background color and a record is = to x (something)? Thanks! More on forums.knack.com
🌐 forums.knack.com
0
0
June 11, 2018
javascript - Change text color based on the background color - Stack Overflow
Is it possible to dynamically change the text color based on the background color using CSS, or JS if it's not possible with CSS? I have a image that comes under the text. My text color is white, b... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Change text color based on brightness of the covered background area? - Stack Overflow
I am looking for a plugin or technique that changes a text's color or switches between predefined images/icons depending on the average brightness of the covered pixels of its parent's background-i... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Determine the best text color for a given background color - User Experience Stack Exchange
What is the best way to determine the best color for a text that will have good contrast and will be pleasing to the eyes (i.e. it can be either white, any shade of grey or black) with the help of More on ux.stackexchange.com
🌐 ux.stackexchange.com
January 14, 2018
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-change-text-color-depending-on-background-color-using-javascript
How to change text color depending on background color using JavaScript? - GeeksforGeeks
January 23, 2023 - <script src= "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <style> #backG { width: 200px; height: 50px; color: white; background: green; margin: 0 auto; } </style> <h1 style="color:green;"> GeeksforGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <button onclick="GFG_Fun()"> click here </button> <br> <br> <div id="backG">This is GeeksForGeeks.</div> <script> var el_up = document.getElementById('GFG_UP'); var rgbValue = [255, 0, 0]; el_up.innerHTML = "Click on the button to select effective pattern."; function setColor() { rgbValue[0]
🌐
W3Schools
w3schools.com › jsref › prop_style_backgroundcolor.asp
HTML DOM Style backgroundColor Property
The backgroundColor property sets or returns the background color of an element. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: sales@w3schools.com · If you want to report an ...
🌐
Knack
forums.knack.com › ask the community › get answers
Javascript code for text color and background color - Get Answers - Knack Community Forum
June 11, 2018 - Hi Everyone, Does anyone have a javascript code to let me change text and background color and a record is = to x (something)? Thanks!
Top answer
1 of 9
249

Interesting resources for this:

  • W3C - Ensure that foreground and background color combinations provide sufficient contrast
  • Calculating the Perceived Brightness of a Color

Here's the W3C algorithm (with JSFiddle demo too):

const rgb = [255, 0, 0];

// Randomly change to showcase updates
setInterval(setContrast, 1000);

function setContrast() {
  // Randomly update colours
  rgb[0] = Math.round(Math.random() * 255);
  rgb[1] = Math.round(Math.random() * 255);
  rgb[2] = Math.round(Math.random() * 255);

  // http://www.w3.org/TR/AERT#color-contrast
  const brightness = Math.round(((parseInt(rgb[0]) * 299) +
                      (parseInt(rgb[1]) * 587) +
                      (parseInt(rgb[2]) * 114)) / 1000);
  const textColour = (brightness > 125) ? 'black' : 'white';
  const backgroundColour = 'rgb(' + rgb[0] + ',' + rgb[1] + ',' + rgb[2] + ')';
  $('#bg').css('color', textColour); 
  $('#bg').css('background-color', backgroundColour);
}
#bg {
  width: 200px;
  height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="bg">Text Example</div>

2 of 9
127

This article on 24 ways about Calculating Color Contrast might be of interest to you. Ignore the first set of functions because they're wrong, but the YIQ formula will help you determine whether or not to use a light or dark foreground color.

Once you obtain the element's (or ancestor's) background color, you can use this function from the article to determine a suitable foreground color:

function getContrastYIQ(hexcolor){
    var r = parseInt(hexcolor.substring(1,3),16);
    var g = parseInt(hexcolor.substring(3,5),16);
    var b = parseInt(hexcolor.substring(5,7),16);
    var yiq = ((r*299)+(g*587)+(b*114))/1000;
    return (yiq >= 128) ? 'black' : 'white';
}
🌐
GitHub
github.com › brycejech › textContrast
GitHub - brycejech/textContrast: JavaScript Library for Setting Text Color According to Background-Color
<style> .bg { display: inline-block; float: left; padding: 25px; border: 1px solid black; color: black; } .bg-green { background-color: green; } .bg-yellow { background-color: yellow; } .bg-purple { background-color: purple; } .bg-red { background-color: red; } .bg-orange { background-color: orange; } .bg-black { background-color: black; } .bg-white { background-color: white; } </style> <script src="/js/text-contrast.min.js"></script> <div class="bg bg-green">Some Text</div> <div class="bg bg-yellow">Some Text</div> <div class="bg bg-purple">Some Text</div> <div class="bg bg-red">Some Text</di
Author   brycejech
Find elsewhere
🌐
Go Make Things
gomakethings.com › dynamically-changing-the-text-color-based-on-background-color-contrast-with-vanilla-js
Dynamically changing the text color based on background color contrast with vanilla JS | Go Make Things
Last month, we looked at a technique for generating random colors with vanilla JS. Reader Stephen Flannery showed me a demo he built with the technique where the text color changed from black to white if the color was too dark. Checking color contrast with vanillia JS When I asked Stephen how ...
Top answer
1 of 2
4

Don't get fooled into thinking that you need to find the best shade of grey to use.

Given any background color, the foreground color that provides the highest contrast ratio will be either white or black, and not some shade of grey in between.

Having said that, pure black or white can seem a little harsh and less pleasing to the eyes - too much contrast can be quite distracting for some users. So, assuming for the purposes of this answer that black means off-black (eg #101010), and white means off-white (eg #f0f0f0), the question then becomes "is black or white better for my background color"?

In another answer I go into more detail with some good example screenshots of how contrast ratio varies for ranges of backgrounds.

In summary, for any two given colors there is a formula for contrast ratio:

The contrast ratio is calculated as (L1 + 0.05) / (L2 + 0.05), where

L1 is the: relative luminance of the lighter of the colors, and

L2 is the relative luminance of the darker of the colors.

In your case you simply need to calculate the contrast ratio for white and your bg color; and again for black and your bg color, and then pick black or white depending on the highest contrast ratio.

2 of 2
3

'Pleasing to the eyes' is very subjective.

But there are a lot of contrast tools like http://leaverou.github.io/contrast-ratio/ and https://contrastchecker.com which take in to account brightness contrast as well as hue contrast. Many of these tools are based on WCAG guidelines which makes them fairly standardized in their outcomes, and therefore widely used and accepted.

🌐
Scriptcase
forum.scriptcase.net › scriptcase 8 › discussion
Change Button text and/or background color with javascript? - Discussion - Scriptcase Low-code
September 16, 2014 - Hi, i have a button “MyButton” and would like change the text and/or background color: echo "<script>document.getElementById('sc_btnMyButton_top').bgcolor='red';</script>"; echo "<script>document.getElementById('s…
🌐
CodePel
codepel.com › home › vanilla javascript › javascript text color based on background
JavaScript Text Color Based on Background — CodePel
February 16, 2025 - Here is a free JavaScript code snippet to change text color based on background. You can view demo and download code.
Address   Rafi Qamar Road, Al-Majeed Peradise Al Majeed Peradise, 62300, Bahawalpur
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-change-the-background-color-after-clicking-the-button-in-javascript
How to change the Background Color after Clicking the Button in JavaScript? - GeeksforGeeks
Using JavaScript to change the background color involves adding an event listener to a button, which triggers a function to set the background color property of an element, dynamically altering the background when the button is clicked.
Published   April 30, 2025
🌐
Wunnle
wunnle.com › dynamic-text-color-based-on-background
Dynamic text color based on background | Wunnle Blog
March 23, 2020 - TL;DR: If you want your text color to change to black or white dynamically according to background color contrast, you can use the following code: See it in…
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › CSS › background-color
background-color - CSS - MDN Web Docs - Mozilla
Color contrast ratio is determined by comparing the luminance of the text and background color values. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for larger text such as headings.
🌐
SoftAuthor
softauthor.com › home › javascript › change background color using javascript
Change Background Color Using JavaScript
December 29, 2025 - You can use the style.backgroundColor property directly in JavaScript to change a background colour of an HTML element. The below example will change the background color of the body element to red as soon as the HTML document loads on the browser.
🌐
CodePen
codepen.io › danieledesantis › pen › QWWrLWE
Change text color based on background color
Reverse text color based on background color automatically using only CSS with mix-blend-mode property....
🌐
Delft Stack
delftstack.com › home › howto › javascript › javascript change background color
How to Change the Background Color in JavaScript | Delft Stack
March 11, 2025 - Learn how to change the background color in JavaScript using the backgroundColor property. This article provides various methods, including changing the color on page load, through button clicks, and generating random colors.
🌐
Reddit
reddit.com › r/react › how to change text color based on background color dynamically
r/react on Reddit: How to change text color based on background color dynamically
September 15, 2024 -

I'm working on a landing page with a scrollspy navigation bar on the left. I want the scrollspy's color and text colors to change dynamically based on the background color.

For example, if the section has a dark background, I want the scrollspy to have a light color (and vice versa). I'm stuck on how to detect the background color of sections and adjust the scrollspy's color accordingly.

Please provide me a solution for this!!!!!!

I have edit the details for this question on stackoverflow link

https://stackoverflow.com/q/78987758/22625136