EN
JavaScript - find all forms on web page
0
points
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 windowloadevent or at the end of the script to make sure that all items are loaded before the function execution.