What is the correct way to merge getElementsByClassName results in plain JavaScript?

Merging HTMLCollections with concat behaves oddly. Try this instead:

const mergedList = Array.from(document.getElementsByClassName('traceElement'))
  .concat(Array.from(document.getElementsByClassName('alertElement')));

In my work merging HTMLCollections, I often prefer converting the collections into arrays using the spread operator. I usually do something like: let list1 = […document.getElementsByClassName(‘traceElement’)]; then do the same for any additional collections. By merging these new arrays with the concat method, I’m able to work with a full array that supports array functions like filter or sort. This approach reliably converts the live collections into static arrays, helping me avoid side effects that come with HTMLCollections updating automatically. It’s a straightforward method that has worked well in my various projects.

i sometimes use .slice.call for a quick conversion: let merged = .slice.call(document.getElementsByClassName(‘traceElement’)).concat(.slice.call(document.getElementsByClassName(‘alertElement’))); this method also works flawlessly.