10

JavaScript has an exciting API for monitoring changes made to HTML elements. The API is called the MutationObserver API, and it was invented at the prestigious W3C—the global organization comprised of our genius software engineer overlords.

Unfortunately, the W3C has a history of occasionally forgetting to proofread new specifications before publishing them, after their large army of monkeys with typewriters have produced working draft specifications, but I'm sure those mistakes are all in the past. The MutationObserver API is receiving praise online. I'm sure it's well designed!

Let's dive in to how it all works.

The API works by calling (1) a specific function of yours any time (2) a specific kind of change is made to (3) a specific HTML element—all three configurable by you.

When a change occurs, your function is passed a collection of information about the change, known as a "record".

If you ask, that record can even include information about the state of the HTML element before the change occurred, available under the `oldValue` property. How convenient!

Oh, and one more thing. If several changes happen in a short window of time, your function may receive a whole list of records—instead of being run once for each change. You know, to save on computer resources.

Anyway, let's start using this powerful API! But wait, what's that?

The record doesn't contain the state of the HTML element when the change occurred?

No problem! That information doesn't have to be included in the record. I can just look at the element as it appears right now.

But what's this, now? I'm receiving a long list of records. I guess lots of changes happened in a short window of time, so all the records are bundled together.

So how do I know what the state was for each record?

If I look at the element as it appears right now, I can only see the end result. That won't tell me what the state was after each individual change.

I guess there's only one way to find out. For each record, I need to look at the next record and check that record's `oldValue` property.

I need to write look-ahead logic just to see the state at each record!

What kind of monkey wro—oh, right. The W3C wrote the MutationObserver API.

Just forget that I asked.

Comments
Add Comment