Simplified Text Replacement in HTML

JavaScript developers frequently have to replace parts of text on a webpage. Sometimes it is a hassle, as there are multiple small pieces of text that need to be replaced inside of a larger element (such as numbers or madlibs). Today's code snippet finds each var node inside of a parent element and returns an object with a substitute function. This function simplifies replacing the content inside the var elements.

Getting started…

Create HTML markup with several var elements that need their content replaced:

<div id="id_test">
  My name is <var class="name">INSERT NAME HERE</var>. 
  I enjoy <var class="activity">INSERT ACTIVITY HERE</var>. 
  I like to play <var class="sport">INSERT SPORT HERE</var>.
</div>

How to do it…

Here is a YUI 3 version of a function that finds all var elements inside of a node and returns an object with a substitution function:

function build_replacement_object(elNode) {
  var elVars = {};

  elNode.all('var').each(function(el, i) {
    if (el.get('className')) {
      elVars[el.get('className')] = el;
    }

    elVars[i] = el;
  });

  return {
    substitute: function(o, value) {
      if (elVars[o]) {
        elVars[o].setContent(value);
      }
    }
  };
}

Here is the same function, using Just Plain JavaScript (JPJS):

function build_replacement_object(elNode) {
  var elVars = {},
  elNodes = elNode.getElementsByTagName('var'),
  i = 0, j = elNodes.length,
  el;

  for (; i < j; i += 1) {
    el = elNodes[i];
    
    if (el.className) {
      elVars[el.className] = el;
    }

    elVars[i] = el;
  }

  return {
    substitute: function(o, value) {
      if (elVars[o]) {
        elVars[o].innerHTML = value;
      }
    }
  };
}

You can index the var element to be replaced by the order they appear in the DOM:

// YUI 3 signature, requires a Y.Node instance to be passed into function
var o = build_replacement_object(Y.one('#id_test'));
o.substitute(0, 'Matt Snider');
o.substitute(1, 'Video Games');
o.substitute(2, 'Soccer');

Or you can replace using the class attribute value of the var elements:

// JPJS, requires an HTML element
var o = build_replacement_object(document.getElementById('id_test'));
o.substitute('name', 'Matt Snider');
o.substitute('activity', 'Video Games');
o.substitute('sport', 'Soccer');

How it works&hellips;

Each version of the build_replacement_object function simply finds all the var elements in the descending DOM tree and creates a map of them, keyed by an index of the order they appear and any class that might be applied. The returned object has a substitute function that requires a key or index as the first argument and a string as the second. When used, the substitute function replaces the innerHTML of the matching var element with the replacement text.