Skip to main content
A Frehner Site

HTMLCollections Are Nice, Actually

They're Not Arrays #

In the past I've avoided using DOM APIs that return an HTMLCollection because it was annoying to have to convert them into an array to really work with them.

And to be fair, that problem still exists, so that's not fun.

However, I recently built out a test implementation of cellIndex for a custom web component, and it turns out that I really liked using an HTMLCollection in this instance. For example, this code demonstrates (at a basic level - error handling and whatnot left out) what I did:

class TableRow extends HTMLElement {
	#cellHtmlCollection: HTMLCollectionOf<TableCell>;

	connectedCallback() {
		this.#cellHtmlCollection = this.getElementsByTagName("ui-table-cell");
	}

	getIndexForCell(cellElement: TableCell) {
		return Array.from(this.#cellHtmlCollection).indexOf(cellElement);
	}
}

class TableCell extends HTMLElement {
	get cellIndex() {
		return this.closest("ui-table-row").getIndexForCell(this);
	}
}

Yes, I had to convert it to an Array here. But here's why I still liked using it:

They're Live, and Lazy, Just Like Me #

The thing I really like about this is that I don't need to do complex things to keep my collection of TableCells updated - such as attaching a mutation observer. That's because HTMLCollections are live, meaning they're automatically kept up-to-date by the browser; every time you access it, you'll be getting a live view of the DOM.

I also found this article that goes a bit more in-depth on how getElementsByTagName() is also quite a bit faster (because it's lazy) than querySelectorAll(), which is a nice bonus.

Use the platform, I guess? :)