Give all elements different background-colors with Javascript

I have a table with a variable amound of span-Elements (Bootstrap badges). Some of them have the same ID and some a different ID. I want each unique span-Element to have a unique color. Those colors should be dark enough to be a good background for white text and they should be as different (colofrul) to other elements as possible.

This is where I’m at:
enter image description here

This is how I apply different background-colors to them with JavaScript:

// Find all span-elements with .aktiviert in #region-main
const aktiviertSpans = document.querySelectorAll("#region-main .aktiviert");
const idColors = new Map();
let hue = 0;

// loop through all span-elements
for (let i = 0; i < aktiviertSpans.length; i++) {
    const span = aktiviertSpans[i];
    const id =;

    // If ID exists, give her the existing color
    if (idColors.has(id)) { = idColors.get(id);
    } else {
        // else create a new color
        const color = `hsl(${hue}, 100%, 25%)`;
        idColors.set(id, color); = color;
        hue = (hue + (360 / idColors.size)) % 360;

Now I have two issues/question:

  1. Is this a good approach or is there a better way? Would it be possible to include bright colors and black text as soon as too many entries exist?
  2. For some reason the first two entries get the same background-color (see “Max” and “Susanne”). How can I fix this?