Modelesq Modelesq - 6 months ago 49
Javascript Question

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

returns an array like so...


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


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 []

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 => {
  <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>