ID-Assigned DOM Elements and Global Properties
In a previous question, it was observed that specific DOM elements with IDs are accessible as variable names or properties of the window object in Internet Explorer and Chrome. For instance, for the HTML element:
<div>
The innerHTML property can be retrieved as follows:
alert(example.innerHTML); // Alerts "some text". alert(window["example"].innerHTML); // Alerts "some text".
This raises the questions:
Properties and Global Accessibility
The intended behavior is for named elements to become apparent properties of the document object. However, this approach is problematic as it allows element names to conflict with actual document properties.
Microsoft Internet Explorer exacerbated the issue by assigning named elements as properties of the window object. This further complicates matters by requiring avoidance of element names that match any member of the document or window object.
Issues with Global Accessibility
Additionally, named elements become visible as global-like variables. While global variable and function declarations typically overshadow them, assigning a value to a global variable with a matching name can result in errors in Internet Explorer.
Best Practices
It is generally discouraged to rely on named elements as global properties or to omit the var declaration when creating global variables. Adhering to document.getElementById is recommended due to its wider support and reduced ambiguity. Consider using a simple wrapper function with a shorter name if typing becomes an issue.
Caching and Browser Optimization
Maintaining an id-to-element lookup cache is generally unnecessary as browsers often optimize the getElementById call using a quick lookup. Potential issues arise when elements change IDs or are added/removed from the document.
Standardization and Future Implications
The HTML5 specification now codifies the previously non-standard practice of adding named elements to document and window properties. This means that Firefox 4 will also support this functionality.
Conclusion
While it is possible to access DOM elements with IDs as global properties in certain browsers, this practice is discouraged due to potential conflicts and ambiguity. It is better to rely on document.getElementById or a simple wrapper function.
The above is the detailed content of Can I Access DOM Elements by ID as Global Properties, and Should I?. For more information, please follow other related articles on the PHP Chinese website!