[JavaScript] Working with DOM Collections: Array.from(), filter(), and forEach()

Working with DOM Collections: `Array.from()`, `filter()`, and `forEach()`


When working with the DOM in JavaScript, many native collections — like HTMLCollection or NodeList — are array-like but not full arrays. This means common array methods like .filter() and .forEach() may not be directly available. I needed to use this combination when I needed to keep certain element under another element while removing the rest.

Converting to a Real Array: Array.from()


DOM methods like .children or .querySelectorAll() return HTMLCollection or NodeList — these can’t use .filter() or .map() directly.
const buttons = document.querySelectorAll('button');
buttons.filter(...); // ❌ TypeError

Convert them into an array using Array.from()

const realArray = Array.from(buttons);
realArray.filter(...); // ✅ Now works

Or use spread syntax:

const realArray = [...buttons];

Selecting a Subset: .filter()

Once the list is a real array, .filter() can be used to keep only elements that meet a condition.

Example: remove all children of a container except one with a specific ID:

const children = Array.from(container.children);
const toRemove = children.filter(child => child.id !== 'cancelButton');
toRemove.forEach(child => child.remove());

Running an Action for Each Element: .forEach()


.forEach() lets you perform an action on every element of an array. But this is not a loop but a function

Used after .filter():

toRemove.forEach(child => child.remove());

Used alone:
Array.from(container.children).forEach(child => {
  console.log(child.tagName);
});

Comments