How to Get a Parent Form Element From a Child Input Element Using JavaScript?

Find out how to get the containing form element from an input form element using JavaScript

All HTML form element objects accessed via JavaScript (such as HTMLInputElement, HTMLTextAreaElement, HTMLButtonElement, etc.) have the property "form" which refers to their parent form element. To demonstrate this, let's assume we have the following HTML form:

<form id="my-form">
    <input type="text" id="name-field" name="name" />
    <textarea id="msg-field" name="msg"></textarea>
    <button id="btn-submit" type="submit">Submit</button>
</form>

Now, to retrieve the form element from any of the input elements we can do any of the following:

const form = document.getElementById('name-field').form;
const form = document.getElementById('msg-field').form;
const form = document.getElementById('btn-submit').form;

Similarly, if we had an event target that we knew was a form input element, we could access its parent form element like so:

const form = event.target.form;

Consider, for example:

const elem = document.getElementById('name-field');

elem.addEventListener('focus', function (e) {
    console.log(e.target.form);
}, false);

Following on from the example above, if you wish to get the form as FormData object, you can simply pass the form element as an argument to the FormData object at the time of instantiation like so:

const formData = new FormData(e.target.form);

If you're using TypeScript, you may encounter the error "Property 'form' does not exist on type 'EventTarget'" while trying to access the form property on the event target. To fix this, simply assert the type of the event target to the appropriate HTML form input element type. For example:

const elem = document.getElementById('name-field');

elem.addEventListener('focus', function (e) {
    const target = e.target as HTMLInputElement;
    console.log(target.form);
}, false);

You can also inline the assertion like so:

(e.target as HTMLInputElement).form;

To learn more about this, check out our article, "How to Fix "Property '...' does not exist on type 'EventTarget'" TypeScript Error".


Hope you found this post useful. It was published . Please show your love and support by sharing this post.