Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

form.getElementsByName is not a function, but document.getElementsByName is

This first example (type="button" is intentional) should work:

<form class="needs-submission">
    <input type="hidden" name="id" value="1">
    <input type="text" name="name">
    <input type="button" name="save" value="Save Changes" onclick="saveChanges(this.closest('.needs-submission'))">
</form>
function saveChanges(form) {
    const id = document.getElementsByName('id')[0]
    const name = document.getElementsByName('name')[0]
    const save = document.getElementsByName('save')[0]
}

However, when I want to select the same fields from the perspective of the form rather than the whole document, form.getElementsByName is not recognised as a function.

function saveChanges(form) {
    const id = form.getElementsByName('id')[0]
    const name = form.getElementsByName('name')[0]
    const save = form.getElementsByName('save')[0]
}
Uncaught TypeError: form.getElementsByName is not a function
    at saveChanges
    at HTMLInputElement.onclick

But form.getElementsByTagName seems works fine?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function saveChanges(form) {
    const id = form.getElementsByTagName('input')[0]
    const name = form.getElementsByTagName('input')[1]
    const save = form.getElementsByTagName('input')[2]
}

My question is: Why can’t I get the fields by their name attribute? Do document and form have different datatypes?

>Solution :

According to MDN, getElementsByName is a function of the Document object (so it only exists for the global document object, not for every HTML element): https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByName

As a workaround, you could use a query selector to find the element like this:

const name = form.querySelector("input[name='name']");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading