Modelesq Modelesq - 5 months ago 36
Javascript Question

form.elements.filter is not a function when trying to weed out button inputs

form.elements
returns an array like so...

[
input#user_name,
input#user_email,
button#submit,
...
]


I'm trying to filter out the button inputs

<button type="submit" className="btn" id="edit">Save</button>

form.elements.filter(i => (
i.tagName !== 'BUTTON'
)).forEach(i => (// store stuff));


Why wouldn't this work? returns
form.elements.filter is not a function

Answer

form.elements returns a HTMLFormControlsCollection.

filter does not exist as an operation on a HTMLFormControlsCollection, along with some other array methods, like forEach.

You could convert to an array first in a number of ways. As pointed out by @DavidThomas, since you are using arrow functions you should be able to use Array.from

var els = Array.from(form.elements);
// Otherwise, use [].slice.call(form.elements)

Now you can do any array operations normally, including forEach, filter, etc.

els = els.filter(el => (
    el.tagName !== 'BUTTON'
))

Here is a full example:

var form = document.querySelector('form');
var els = Array.from(form.elements);

els = els.filter(el => {
  return (
    el.tagName.toLowerCase() !== 'button' &&
    el.getAttribute('type') !== 'button'
  );
});

els.forEach(el => {
  console.log(el);
});
<form>
  <input type="text" value="1">
  <input type="button" value="Input Button">
  <textarea>Awesome Content</textarea>
  <button>Another Button</button>
  <button type="submit" className="btn" id="edit">Save</button>
</form>