In the realm of JavaScript development, a perplexing issue arises when function names clash with element IDs. This query delves into the underlying reasons and explores the restrictions and implications of such conflicts.
Consider the following example:
<script> function border(border) { alert(border); } </script> <select>
In the first fiddle, this code successfully alerts the selected option's value. However, in the second fiddle, using a form element (with a form surrounding the select), the code fails with the error "border is not a function."
This discrepancy stems from a legacy issue in JavaScript, where the scope chain of event-handler attribute values includes the enclosing Form object. This Form object possesses properties representing the names of its child controls, including the border select element.
Thus, when referring to border as the function in the event handler within the form context:
<form><… name="border" onchange='border(this.value)' …></form>
This is equivalent to calling form.border(this.value), which references the Form object's property instead of the intended function.
The JavaScript language specification does not explicitly forbid naming conflicts between functions and element IDs. However, the DOM Level 2 HTML Binding specifies that HTMLCollections (including forms and their controls) can be accessed by name or ID using bracket syntax.
This implies that:
Using the same identifier for both an element and a function can:
To avoid these issues, consider following these guidelines:
The above is the detailed content of Why Do JavaScript Function Names Sometimes Conflict with Element IDs?. For more information, please follow other related articles on the PHP Chinese website!