try catch finally

Using try catch with errors by design

by David McClelland

HTML

<div id="age">
  Age: 34</div>
<div class="noId">no ID</div>

JavaScript

//example one: expected use where a div with ID exists
//changeInnerHTMLByIdOrExisting("age", "Age: 35", "Age: 34");
//example two: find expected matching HTML contents of a node, update it and set the id to the expected value
//changeInnerHTMLByIdOrExisting("missingId", "Age: 36", "no ID");
//example three: no matching id or content found: create the entire node
changeInnerHTMLByIdOrExisting("missingNode", "Age: 37", "no Value");

function changeInnerHTMLByIdOrExisting(id, update, existing) {
  try {
    var newElement = undefined;
    document.getElementById(id).innerHTML = update;
  } catch (error) {
    try {
      var elements = document.getElementsByTagName('*');
      for (var i = 0, x = elements.length; i < x; i++) {
      console.log(elements[i].innerHTML);
        if (elements[i].innerHTML === existing) {
        alert("Match found");
          elements[i].innerHTML = update;
          id = elements[i].id;
          break;
        }
      }

      if (i === x) {
        throw new Error("An existing element was not found.");
        changeInnerHTMLByIdOrExisting("age", "Age: 35", "Age: 34");
      }
    } catch (error2) {
      alert(error2.message + "\nCreating new text node.");
      newElement = document.createTextNode(update);
      document.body.appendChild(newElement);
    }
  } finally {
    if (newElement !== undefined) {
      console.log("Returning new text node...");
      return newElement;

    } else {
      console.log("Modified element \"" +
        (id || existing) +
        "\" with inner HTML \"" +
        update + ".");
    }
  }
}