NodeWalker in JavaScript

For tasks like “transform every text node”.

Assumed audience: People with basic familiarity with JavaScript’s document APIs.

I wanted to fix up every single text node in a particular document I was reading just now (doing some research): replacing the old-school use of ``quoted'' with “quoted” so I could be less annoyed by it.1 I knew I could write a little script that recursively walked every part of the DOM tree using querySelectorAll and Node.childNodes, and doing something with the node only when it is a text node. I have done that before. It’s kind of annoying!

So I wondered: is there an easier way to do this? A quick search taught me that the Document.createTreeWalker API exists, which makes this trivial!

Here’s what I did:

let walker = document.createTreeWalker(document, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
  walker.currentNode.data = walker.currentNode.data
    .replace("''", "”")
    .replace("``", "“")
    .replace("'", "’")
    .replace("`", "‘");
}

It’s funny to me that despite my having written JavaScript for fifteen years, my having been a specialist in the language for most of a decade, and the language itself having a hilariously small standard library, I still find new APIs like this all the time.


Notes

  1. Yes, this is indeed a little window into my mind. Yes, it really is this persnickety in here. ↩︎