Global Variable Access of HTML Element IDs
The question arises regarding the appropriate handling of accessing HTML element IDs through global variables. In the given example, Chrome allows direct access to an element with ID "a" via a.stuff(), while Firefox requires the use of document.getElementById('a').
Specification
The HTML4 specification does not explicitly outline this behavior. However, it does not prohibit the practice of making element IDs into global variables either. The WHATWG HTML spec currently mandates this behavior, considering global access of element IDs as a legacy or compatibility issue.
Implementation
Major browsers, including Chrome and Firefox (in quirks mode), have adopted this behavior for compatibility reasons. Firefox, however, also allows direct access to elements via global variables in strict mode, but its implementation may be unreliable.
Ambiguity
When both a global variable a and an HTML element with ID "a" exist, the behavior depends on the execution context. In most cases, JavaScript will prioritize the global variable a over the HTML element. However, using global variables for element IDs is generally frowned upon due to potential conflicts and namespace pollution.
Special Characters in HTML IDs
HTML IDs can contain hyphens (-), colons (:), and periods (.), characters that cannot be used in JavaScript identifiers. To access these elements through global variables, browsers would translate them. For instance, an element with ID "foo-bar" might be accessible via the global variable foo-bar.
Conclusion
While the practice of making element IDs global variables has historical support, it is not explicitly specified in the HTML4 spec. The WHATWG HTML spec requires this behavior, but recommends using document.getElementById() or other methods for accessing elements. Using global variables for element IDs should be avoided due to confusion and potential conflicts with other variables in the global namespace.
The above is the detailed content of Why Can I Sometimes Access HTML Element IDs Directly as Global Variables in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!