Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope changes during HTML parsing

Tags:

html

dom

scope

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?

like image 832
Tibrogargan Avatar asked May 31 '26 14:05

Tibrogargan


1 Answers

The WHATWG HTML Standard defines 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().

like image 104
progysm Avatar answered Jun 02 '26 18:06

progysm