'Can i put css on a condition required in javascript?

I want to know if there is a way to add css on a required element in JavaScript I have many condition and i want it just in this case i want something like that (I know i can't do this) Thanks for your help !

  if (!allAreFilled) {                                          // While required element are empty
        alert('Fill all the fields');
        objForm.style:required.border = "solid 1px red";            // objForm = document.getElementById('compoundFormId')
      }


Solution 1:[1]

With css:

input:required {
  border: 1px dashed red;
}

Solution 2:[2]

You cannot directly change CSS style settings for pseudo elements or classes in Javascript.

But you can set CSS variables from JS.

This snippet sets a CSS variable --border when the submit button is clicked with the value depending on a condition.

const button = document.querySelector('button');
let conditionIsSet = true;

button.addEventListener('click', function() {
  document.body.style.setProperty('--border', (conditionIsSet) ? 'red' : 'black');
});
body {
  --border: black;
}

input:required {
  border: var(--border) 1px solid;
}
<input type="checkbox" onchange="conditionIsSet = !conditionIsSet;">Select condition is true</input>
<br> Input without required: <input> Input with required: <input required>
<button>Submit</button>

Obviously you need to supply whatever condition is needed.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tushar Shahi
Solution 2 A Haworth