Search code examples
javascript

Using innerHTML with querySelectorAll


I want to use something similar to the following to clear errors in a form upon a resubmission attempt:

document.querySelectorAll("#form-error-name, #form-error-email, #form-error-tel, #form-error-dob, #form-error-password, #form-error-goal").innerHTML= "";

...But the contents of the divs isn't cleared. What am I doing wrong?


Solution

  • You'll need to loop through the results

    var errors = document.querySelectorAll(
        "#form-error-name, 
         #form-error-email, 
         #form-error-tel, 
         #form-error-dob, 
         #form-error-password, 
         #form-error-goal");
    
    [].forEach.call(errors, function(error) {
        error.innerHTML = '';
    });
    

    querySelectorAll doesn't return an array, but a NodeList, which doesn't have a forEach method on its prototype.

    The loop above is using the forEach method on the array object's prototype on the NodeList object.