Home > other >  form.getElementsByName is not a function, but document.getElementsByName is
form.getElementsByName is not a function, but document.getElementsByName is

Time:11-22

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?

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?

CodePudding user response:

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']");
  • Related