Is there a way, to get this more flexible, variable and more compressed?

here is my suggestion

function onChangeHandler(event) {
 const element = event.target;
 
 element.style.backgroundColor = element.valid ? colorValidityOk : colorValidityNotOk;
}

Then call that on a loop

myElements.forEach(element => element.onChange(onChangeHandler))

And you went from 15 lines of code to 5 clean code