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:
xxxxxxxxxx
1
var forms = document.forms;
or:
xxxxxxxxxx
1
document.querySelectorAll('form');
In this example, we use document.forms
property that contains a collection of the forms in the current HTML document.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<form id="form1">
5
<input type="button" value="button1"/>
6
</form>
7
<script>
8
9
var forms = document.forms; // contains all forms
10
11
12
// Usage example:
13
14
window.addEventListener('load', function() {
15
console.log([forms]);
16
});
17
18
</script>
19
<form id="form2">
20
<input type="button" value="button2"/>
21
</form>
22
</body>
23
</html>
In this example, we use querySelectorAll()
method to get the collection of all forms on the web page.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<form id="form1">
5
<input type="button" value="button1"/>
6
</form>
7
<script>
8
9
function findForms() {
10
return document.querySelectorAll('form'); // finds all forms
11
}
12
13
14
// Usage example:
15
16
window.addEventListener('load', function() {
17
console.log([findForms()]);
18
});
19
20
</script>
21
<form id="form2">
22
<input type="button" value="button2"/>
23
</form>
24
</body>
25
</html>
Note:
The
findForms()
function needs to be executed after windowload
event or at the end of the script to make sure that all items are loaded before the function execution.