Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using innerHTML with querySelectorAll

Tags:

javascript

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?

like image 450
user2265915 Avatar asked Jan 16 '15 11:01

user2265915


2 Answers

The question wants .innerHTML, but that's not valid on input; you actually want .value. The appropriate modern answer would be

[... document.querySelectorAll('input')]
  .map(i => i.value = '');
like image 183
John Haugeland Avatar answered Oct 29 '22 17:10

John Haugeland


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 node list, 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.

like image 30
atmd Avatar answered Oct 29 '22 19:10

atmd