Search code examples
javascriptjqueryperformancemethodschaining

Removing a class from ALL matched form elements.. cleanest way?


I'm trying to clear a bunch of error styling on form elements whenever top level radio buttons are checked. I'm trying to find:

  • Alternative methods and structure for improving performance
  • A chaining method for finding all the form elements so I'm not making so many calls.. (not sure if possible).

    // Global variable OR scoped variable defined just before calling functions below..

JS

var target = jQuery("#cachedElement");


function functionWithManyReferencesToTarget() {
    target.find("input").each(function() {
    $(this).removeClass("formError error-state");
});
target.find("label").each(function() {
    $(this).removeClass("formError error-state");
});
target.find("select").each(function() {
    $(this).removeClass("formError error-state");
});
}

Solution

  • $target.find('input, label, select').removeClass('formError error-state');