Tibrogargan Tibrogargan - 4 months ago 9
HTML Question

Scope changes during HTML parsing

If you create a form in HTML like so:

<!DOCTYPE html>
<html><head>
<script>
function submit() {
console.log("window.submit");
}
</script>
</head>
<body>
<form name="form">
<input type="button" value="button" onclick="submit()" />
</form>
</body>
</html>


When the
input
tag is parsed (in chrome at least), the corresponding DOM element will apparently be created with the form as the scope, so that the function bound to the onclick handler will be
form.submit()
rather than
window.submit()
. Is this standard behavior or browser dependent? Is there any documentation that covers this?

Answer

WhatWG HTML5 Specs define it in Event Handler Attributes https://html.spec.whatwg.org/multipage/webappapis.html#event-handler-attributes

Scope

    - If H is an element's event handler, then let Scope 
    be NewObjectEnvironment(document, the global environment).
    - Otherwise, H is a Window object's event handler: let Scope be the global environment.
    - If form owner is not null, let Scope be NewObjectEnvironment(form owner, Scope).
    - If element is not null, let Scope be NewObjectEnvironment(element, Scope).

In this case, since form owner is not null, every property of the Form will be in the scope. "submit" is a property of form, so "submit()" will call form.submit().

Comments