liveBook · Manning

DOM clobbering

As explained in Secrets of the JavaScript Ninja, Second Edition

Browser behavior in which form controls named by their id or name create or replace properties on their containing form element.

A form control can unexpectedly take over a property on its containing form. Browsers expose controls through their id or name values, so a control named action or submit can replace the form’s corresponding property and disrupt JavaScript that uses it. section 14.2.3

<form id="form" action="/conceal">
  <input type="text" id="action"/>
  <input type="submit" id="submit"/>
</form>

Here, controls named action and submit collide with form properties of the same names. section 14.2.3

When form.submit stops being a method

After a control with id="submit" is added, form.submit can refer to that input rather than the original method. Calling form.submit() can then produce a script error. section 14.2.3

To avoid and diagnose the problem:

  • Avoid simple id and name values that conflict with standard form properties; submit is a common pitfall. section 14.2.3
  • When a form property seems to have changed unexpectedly, check whether a control has the same id or name. section 14.2.3

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains how form controls replace properties through id or name collisions, illustrates resulting errors, and gives a markup-avoidance practice.
Examples
Uses form controls named action and submit to show property replacement and a failed submit() call.
What you can do after
Diagnose unexpected form properties and avoid collisions by choosing nonconflicting id and name values.
How it connects
Connects DOM clobbering to HTML forms, browser behavior, and JavaScript debugging.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.