Languages
[Edit]
EN

JavaScript - find all forms on web page

0 points
Created by:
Jan-Alfaro
711

In this article, we would like to show you how to find all forms on web page using JavaScript.

Quick solution:

var forms = document.forms;

or:

document.querySelectorAll('form');

 

Practical examples

1. Using document.forms property

In this example, we use document.forms property that contains a collection of the forms in the current HTML document.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <form id="form1">
    <input type="button" value="button1"/>
  </form>
  <script>

    var forms = document.forms; // contains all forms


    // Usage example:

    window.addEventListener('load', function() {
        console.log([...forms]);
    });

  </script>
  <form id="form2">
    <input type="button" value="button2"/>
  </form>
</body>
</html>

2. Using querySelectorAll() method

In this example, we use querySelectorAll() method to get the collection of all forms on the web page.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <form id="form1">
    <input type="button" value="button1"/>
  </form>
  <script>

    function findForms() {
        return document.querySelectorAll('form'); // finds all forms
    }
    
    
    // Usage example:
    
    window.addEventListener('load', function() {
        console.log([...findForms()]);
    });

  </script>
  <form id="form2">
    <input type="button" value="button2"/>
  </form>
</body>
</html>

Note:

The findForms() function needs to be executed after window load event or at the end of the script to make sure that all items are loaded before the function execution.

 

See also

  1. JavaScript - find all HTML comments

  2. JavaScript - find all links on web page

  3. JavaScript - find all images on web page

  4. JavaScript - get src of all images on web page

References

  1. Document.forms - Web APIs | MDN
  2. Document.querySelectorAll() - Web APIs | MDN

Alternative titles

  1. JavaScript - how to get all forms on particular web page?
  2. JavaScript - get all forms on web page
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join