There are several ideas put forward in the question about how to choose between black and white for text color depending on the background color.
Most have been answered one way or another in comments. Taking the ideas one by one:
Can we use CSS mix-blend-mode - no. There is no one setting for this that ensures text will appear readable on all possible backgrounds.
Can we use CSS (the preferred method) - unfortunately no as the div requiring the text color to depend on background color is created by JS at run time.
Can we use JS - yes and as the div is being created by JS and having its background-color set then it might as well have its color set then too.
The JS string is as given in the question with the addition of a setting for color:
'<div style="background-color:' + bgColor + '; color: ' + textBlackOrWhite(bgColor) + ';"'
Here is a snippet which defines the function. The snippet also lets you choose a background color and it then sets a color which (roughly) depends on the 'brightness' of the background. See the SO questions referenced here for further discussion as human color perception is a difficult topic.
//from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
function textBlackOrWhite(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);//also checks we have a well-formed hex number
//from https://stackoverflow.com/questions/596216 the answer by @FranciPenov which gives an approximation: (R+R+G+G+G+B)/6
let itsbright = function () { return ((2*parseInt(result[1], 16) + 3*parseInt(result[2], 16) + parseInt(result[3], 16))/6)>127; }
return result ? (itsbright()) ? '#000000' : '#ffffff' : '#000000';//falls back onto black if bgColor was not a well-formed 3 or 6 digit hex color
}
<div id="div" style="font-family: monospace; box-sizing: border-box; margin: 0; padding: 40px 0; width: 100px; height: 100px; border-style: solid; border-radius: 50%; background-color: black; color: white;text-align:center;">#ffffff</div>
Click to choose background color: <input id="input" placeholder='#00000' type='color' value='#000000'/>
<button onclick="let d = document.getElementById('div'); let i = document.getElementById('input'); d.innerHTML = i.value; d.style.backgroundColor = i.value; d.style.color = textBlackOrWhite(i.value);">Submit</button>