First, I should recall two common ways to access object properties in JavaScript: dot notation and square bracket notation. Points are accessed directly by the attribute name, while square brackets allow dynamic access to attributes using strings or variables. This may be the main difference between the two writing methods.
Next, I need to consider how the two writings will be different in the context of the form. For example, forms in a collection can be accessed by name or index, while elements in a form can be accessed by name or index. If the name of the form element contains special characters or spaces, it may be problematic to use dot numbers at this time, and square bracket notation must be used.
Then, the name in document.form1[str] mentioned by the user may be a variable, while document. uses the string "name" directly as the attribute name. At this time, we need to give an example to illustrate the difference in behavior between the two when name is a variable. For example, if the value of name is "email", then document.form1[name] is equivalent to document.form1["email"], and document. accesses an element named "name", which may not be what the user wants.
It also needs to consider browser compatibility or certain special cases, such as whether the name of a form element conflicts with an existing property or method of the form object. For example, if there is an element in the form named "submit", using the dot notation document. That element will be retrieved, but it may also overwrite the form's native submit method, resulting in an error. This time, it may be safer to use square bracket notation, such as document.form1["submit"] to get the element correctly without calling the submit method.
In addition, there may be a dynamic name, that is, the name of the element is generated dynamically. At this time, square bracket notation must be used because the dot does not support variables as attribute names. For example, when looping through multiple form elements, variables are used instead of fixed attribute names.
Also pay attention to the difference between the name attribute and the id attribute in HTML. Although usually the name and id may be the same, in some cases they may be different, and document. accesses an element whose name attribute is "name", not an id. This may lead to misunderstandings and needs to be clearly stated.
To sum up, I need to explain the differences between the two in points: syntax differences, processing of dynamic attribute names, processing of special characters, conflicts with the form's native attributes or methods, and the use of variables. Use specific examples to show behavior in different scenarios to help users understand when to use which method is more appropriate.
Finally, make sure the answer is clear and easy to understand, with reasonable structure, and includes code examples and precautions, so that users can quickly grasp the differences between the two and apply them correctly in actual coding.
In JavaScript,document.form1[name]
anddocument.
are two types of access forms (<form>
) elements syntax, but their behavior and applicable scenarios are significantly different. The following is a detailed explanation:
1. document. (point notation)
Syntax featuresAccess elements in the form directly through the attribute name, where
name
yesLiteral string(Fixed name).Use scenariosWhen form element
name
is used when an explicit, legal identifier (without special characters or spaces).-
Example
<form name="form1"> <input type="text" name="username"> </form>
Run HTML
// Access the element of name="username"const input = document.;
-
Things to note
If the element's
name
With certain native properties or methods of the form (such assubmit
、action
) conflict, the dot notation will give priority to accessing the form's native properties/methods rather than elements.if
name
Contains special characters (such as spaces, hyphens, etc.), and the dot representation will report an error.
2. document.form1[name] (square bracket notation)
Syntax featuresDynamic access to form elements through strings or variables, where
name
It can be onevariableor dynamically generated string.-
Use scenarios
When you need to dynamically access elements of different names (for example by loops or variables).
Elemental
name
Contains special characters (such asuser-name
) or when conflicting with form native properties/methods.
-
Example
<form name="form1"> <input type="text" name="user-name"> <input type="text" name="email"> </form>
Run HTML
// Dynamic access to elements through variablesconst fieldName = "user-name"; const input1 = document.form1[fieldName]; // Correct access to the element of name="user-name" // Access directly through stringsconst input2 = document.form1["email"]; // Correct access name="email" Elements
-
Things to note
If the element's
name
Conflicts with the form's native properties/methods, the square bracket notation still allows the element to be accessed correctly.Supports dynamic parameters and is suitable for handling scenarios with uncertain names.
Summary of key differences
characteristic | document. |
document.form1[name] |
---|---|---|
grammar | dot representation,name It is a fixed string |
square bracket notation,name Can be a variable or a string |
Special character support | Not supported (such asuser-name There will be an error) |
Support (such asdocument.form1["user-name"] ) |
Dynamic access | Not supported (fixed name must be known in advance) | Support (names can be generated via variables or dynamically) |
Conflict with native attributes | Priority access to the form's native properties/methods | Bypass conflicts and directly access elements |
Sample Scenario
Scene 1: Element name contains special characters
<form name="form1"> <input type="text" name="user-email"> </form>
Run HTML
// Error: Dot notation cannot access name with hyphen// const input = document.-email; // Correct: square bracket notationconst input = document.form1["user-email"];
Scene 2: Dynamically select element names
const fields = ["username", "email", "address"]; (field => { const element = document.form1[field]; (); });
Scenario 3: Name conflicts with form native attributes
html
copy
<form name="form1"> <input type="text" name="submit"> <!-- With form submit() The same name method --> </form>
Run HTML
// Error: The dot notation will call the form's submit() method instead of accessing elements// document.(); // Trigger form submission // Correct: square bracket notation access elementconst submitInput = document.form1["submit"]; ();
Best Practices
If the element name is a legal identifier and there is no conflict, use it first
document.
(More concise).If the name contains special characters, requires dynamic access, or has conflicts, use
document.form1[name]
。For codes that require compatibility and security, square bracket notation is more reliable.
By rationally selecting these two syntaxes, you can operate form elements more flexibly and safely.
usage
1. Use cannot be accepted in FF ("formname"), and can be used in ie.
It is best to change the subscript usage of ["formname"]
2. Unacceptable usage in FF is the usage defined in ie.
It's best to change it to
3. In FF, you cannot directly use the id of the div to obtain the properties of the div, such as
It should be changed to ("divId").
Summary of some usages of JavaScript
The following usage requires adding the attribute onclick to JSP. Taking the selection all as an example, onclick="javascript:allselect()"//javascript can be omitted
Or use function allselect() ("allselectbox").onclick = function();
Select all:
function allselect(){ var form = [0]; var state = ; var length = ; if(length){ for(var i=0;i<length;i++){ [i].checked=state; } }else = state; }
Another way to write all:
function allSelect(){ var items = ("usernames"); var state = ("allselectbox")[0].checked; if(){ for(var i = 0; i < ; i++){ items[i].checked = state; } }else{ = state; } }
Single choice:
function selectitem(){ var form = [0]; var length = ; if(length){ for(var i=0;i<length;i++){ if([i].checked) return true; } }else return ; }
Go to another page:
function topage(page){ var form = [0] = page; ; }
Take the value of the radio box Radio:
function getradiovalue(objradio){ var result = ""; try{ if(typeof()=="undefined"){ for(var i=0;i<;i++){ if(objradio[i].checked){ return objradio[i].value; } } }else{ if() result = ; } }catch(e){result = "";} return result; }
Check the mobile phone format
function validateMobile(){ var form = [0]; if(!==""){ var num = /^1[35]\d{9}$/ if(!()){ alert("The consignee's mobile phone number is incorrect"); return false; } alert("correct"); } }
This is the end of this article about the difference between document.form1[str] and document. For more related document form content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!