How to apply CSS classes using both server-side PHP and client-side JavaScript

I have a stylesheet connected to my HTML page. My starting point looks like this:

<div class="form_wrapper">

Using JavaScript, I can dynamically add a CSS class to show validation errors:

formElement.classList.add('invalid');

This changes class="form_wrapper" to class="form_wrapper invalid".

This works great for client-side validation. However, I also need to handle server-side validation. When users arrive at the page after a form submission with PHP validation errors, I want to pre-apply the error styling.

I tried this approach but it’s not working:

$cssClass = "form_wrapper";
// Need to conditionally add 'invalid' class here
<div class="<?php echo $cssClass; ?>">

How can I properly manage CSS class application from both PHP (server-side) and JavaScript (client-side) for the same elements?

Build your CSS class string conditionally in PHP before outputting to HTML. Start with a base class and add more based on validation state. Something like $cssClass = 'form_wrapper'; if ($validationErrors) { $cssClass .= ' invalid'; } works well. I usually create a small helper function for this logic, especially with multiple form elements that need similar conditional styling. This way your server-side HTML already has the right classes when the page loads, and your JavaScript can still manipulate classes afterward without conflicts. The browser doesn’t care whether classes were added server-side or client-side.

Store your validation state in a PHP variable and use it to build the class string. I usually do something like $errorClass = isset($validationErrors) && !empty($validationErrors) ? ' invalid' : ''; then output <div class="form_wrapper<?php echo $errorClass; ?>">. This way the initial page load already has the right styling when there are server-side validation errors. Your JavaScript will keep working fine since it’s just adding or removing classes from whatever state the element starts in. Just make sure your PHP logic mirrors what your JavaScript validation does so the styling stays consistent.

for sure! just make sure to check if there’s any errrors in php first, then you can add ‘invalid’ like this: $cssClass = 'form_wrapper' . ($hasErrors ? ' invalid' : '');. this way, js will just take over from there.