The difference between this.form and document.forms

Is there a difference between this.form and document.forms (document["forms"]) or are they similar?

Here is the code I wrote to check the difference.

 <form name="myForm" id="myForm"> <input type="text" name="haha" id="myForm" value="laughable" onclick="alert(this.form.haha.value)" /> </form> alert(document.forms.myForm.haha.value); 

Both of them lead to the same.

+4
source share
2 answers

this.form will provide you with the form element form. ( this is a form element)

containing a form element, if that element has a form.

document.forms will provide you with all the forms in the document (if supported!)

forms return a collection (HTMLCollection) of form elements in the current document.

Better use document.getElementById(id)

 var form = document.getElementById(formId); 
+8
source

this.form will return a form property of this as above, regardless of "this" .

"this" can be anything, for example. div, therefore, may not have a form property.

If "this" occurs with reference to a document, then this.form returns exactly the same thing as document.form . But otherwise, do not count on it.

-1
source

All Articles