Is it good practice to express the state of an HTML element--such as whether an input's value is valid--using a CSS class? Would it be better practice to use data attributes, the properties of a JavaScript object representing the element, or some other method? Example:


.error {
    box-shadow: 0 0 8px .1em #b94a48;

.error is appended to any input that fails validation. When the user attempts to proceed, jQuery checks for the class:


if ($('#container').find('.error').length !== 0) {
    // Don't proceed.
  • Short answer: yes.
    – Jules
    Commented Aug 31, 2017 at 23:43
  • Slightly longer answer: This sort of thing tends to happen a lot when using jQuery. It's fairly common practice. If using a larger frontend framework, then state would probably be handled by that and not by CSS class.
    – neilsimp1
    Commented Sep 1, 2017 at 15:50
  • 3
    If you wish to achieve WCAG compliance, or if you wish to cater to people with disabilities, use of only color to indicate an error will leave out people who are blind or colorblind. In addition to adding the .error class, consider using aria-invalid as well as a non-color-based visual indicator, such as an exclamation point adjacent to the field.
    – John Wu
    Commented Sep 2, 2017 at 1:54
  • 1
    As a color blind developer, I can attest to this. I can barely tell the success green and the error red look apart in the recent project I've been working on. Thanks for the suggestion. Commented Sep 2, 2017 at 2:02

1 Answer 1


Using classes to track state is pretty common, for example - in AngularJS: https://docs.angularjs.org/api/ng/directive/form#css-classes

but - remember that css-classes are easily manipulated in the browser, so if you're doing anything other than decoration with the state classes, you may want to consider also saving state in a data-attribute as well (or controller if using a framework)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.