kotarok
2/29/2016 - 3:54 AM

Walk DOM tree to extract textNode and apply given mutator function.

Walk DOM tree to extract textNode and apply given mutator function.

/**
 * Extract textNodes from the tree of given root element. And apply given
 * function to each textNodes.
 * @param  {HTMLElement}   rootEl Target DOM sub tree root.
 * @param  {Function} fn   Processor function
 */
var processTextNodes = function(rootEl, fn) {
  var proceed_ = function(rootEl) {
    [].forEach.call(rootEl.childNodes, function(childNode) {
      if (childNode.nodeType === Node.TEXT_NODE) {
        var dummy = document.createElement('dummy');
        dummy.innerHTML = fn(childNode.data);
        childNode.parentNode.replaceChild(dummy, childNode);
      } else if (childNode.nodeType === Node.ELEMENT_NODE) {
        proceed_(childNode);
      }
    });
  };
  proceed_(rootEl);
  [].forEach.call(rootEl.querySelectorAll('dummy'), function(dummy) {
    dummy.outerHTML = dummy.outerHTML.replace(/<\/?dummy>/g, '');
  })
};