Accessing form elements

how can this method be used in more than one form is on document?

ie

form.elements;


Link to content: JavaScript: Novice to Ninja, 2nd Edition - Section 8

The hook is in this piece of code

const form = document.forms['search'];

That looks for the form with id=“search”… If you want to work with ALL forms, you eliminate the named access and loop through them.

Edit: Another user asked me if I meant name=“search” instead. Did some quick testing, and the forms object works with both…just an FYI.

This quick/dirty loops through all the forms, writes the form id to the console, then loops through each input element on the form to log those ids. But it gives the basic idea. You could put any of the form code from the book inside the loop and it should work.

document.querySelectorAll("form").forEach((form) => {
  console.log(form.id);
  form.querySelectorAll("input").forEach((input) => {
      console.log(input.id);
  });
});

Thanks Dave
For your help I got that now. I have to define the form first. I was mistaking the form variable with the keyword forms of the DOM object.