Abbreviation string to abbr tags

Vanilla javascript - Turns text strings that are abbreviated into abbr tags with titles based on key/value pairs.

by meetaaronsilber

HTML

<div id="d0">
    <p>AFAICT this guy is just ACORN</p><br/>
    <p>JSYK, I just need AFPOE</p>
</div>

CSS

abbr { border-bottom: 1px dotted #333; cursor: help; }

JavaScript

var addAbbrHelp = (function() {
  var abbrs = {
      'AFAICT': 'As Far As I Can Tell',
      'ACORN' : 'Another Completely Obsessive Really Nutty Person',
      'AFPOE' : 'A Fresh Pair of Eyes',
      'JSYK' : 'Just So You Know'
  };

  return function(el) {
    var node, nodes = el.childNodes;
    var word, words;
    var adding, text, frag;
    var abbr, oAbbr = document.createElement('abbr');
    var frag, oFrag = document.createDocumentFragment()

    for (var i=0, iLen=nodes.length; i<iLen; i++) {
      node = nodes[i];

      if (node.nodeType == 3) { // if text node
        words = node.data.split(/\b/);
        adding = false;
        text = '';
        frag = oFrag.cloneNode(false);

        for (var j=0, jLen=words.length; j<jLen; j++) {
          word = words[j];

          if (word in abbrs) {
            adding = true;

            // Add the text gathered so far
            frag.appendChild(document.createTextNode(text));
            text = '';

            // Add the wrapped word
            abbr = oAbbr.cloneNode(false);
            abbr.title = abbrs[word];
            abbr.appendChild(document.createTextNode(word));
            frag.appendChild(abbr);

          // Otherwise collect the words processed so far
          } else {
            text += word;
          }
        }

        // If found some abbrs, replace the text 
        // Otherwise, do nothing
        if (adding) {
         frag.appendChild(document.createTextNode(text));
         node.parentNode.replaceChild(frag, node);
        }

      // If found another element, add abbreviation help
      // to its content too
      } else if (node.nodeType == 1) {
        addAbbrHelp(node);
      }
    }
  }
}());

addAbbrHelp(document.getElementById('d0'));