Hacking the DOM.

I've given a challenge by a friend of mine. Who is a JavaScript guru and lives in Germany.

Posted by Eralp on May 22, 2019

I'm applying to a Coding Boot Camp. When I was checking into their syllabus, I came across with CSS challenge that was posted on CodePen. While I was practising my CSS knowledge and sharing my screen with my German friend, he gave me a JavaScript challenge.

Challange: Everywhere you see the word "Eats", change it to "Tooth".

It turns out that is not that easy. What I mean by that is; I did my google research but could not come up with anything solid.

Where do I start than?

var words = document.querySelectorAll('div')

Since CodePen project was under one <div> I could just select the id of that <div> and go through the DOM.

Oh noooo... I have to iterate through DOM, what about the children or firstChild what is happening? this spose to be a easy challenge.

Do you remember this?

  • <html> is the root node
  • <html> has no parents
  • <html> is the parent of <head> and <body>
  • <head> is the first child of <html>
  • <body> is the last child of <html>

And also this one?

  • parentNode
  • childNodes[nodenumber]
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling

HTMLCollection is an array-like object

MDN says "An HTMLCollection in the HTML DOM is live; it is automatically updated when the underlying document is changed."

I could do something like: var divs = document.getElementsByTagName('div');

Than I could iterate it. Like this:

            
              for (const item of divs) {
                console.log(item)
              }
              // I've got bunch of <div>'s in the console.
            
          

I used for of instead of for in because for in will return items in the list (indexes 0, 1, 2 etc...).

To me, it sounded like too much work going through the DOM and finding

Hello MDN Documents

I did little digging into MDN and found this:

Document​.create​Node​Iterator()

The NodeIterator interface represents an iterator over the members of a list of the nodes in a subtree of the DOM. The nodes will be returned in document order.

A NodeIterator can be created using the Document.createNodeIterator() method, as follows:
         var nodeIterator = document.createNodeIterator(root, whatToShow, filter);
          

After scrolling down to the page I came across with this example:

            
          var nodeIterator = document.createNodeIterator(
          document.body,
          NodeFilter.SHOW_ELEMENT,
          function(node) {
              return node.nodeName.toLowerCase() === 'p' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
            }
          );
          var pars = [];
          var currentNode;

          while (currentNode = nodeIterator.nextNode()) {
          pars.push(currentNode);
          }
            
          

In this example