title: How to Avoid MathJAX Typeset Queue Error when loading new data into DOM
body: <p>My website uses a javascript function to load (via AJAX) math markup into the DOM and then render it with MathJAX.</p>
  
  <p>If the function is called a second time (i.e., to load some new math markup into a DOM element):</p>
  
  <ul>
  <li><p>All works well if MathJAX has finished processing its Typeset queue prior to the second function call.</p></li>
  <li><p>An error appears if MathJAX has NOT finished processing its Typeset queue prior to the second function call.</p>
  
  <p><code>MathJax.js?config=TeX-MML-AM_CHTML&amp;latest:19 Uncaught TypeError: Cannot read property 'contains' of null</code></p></li>
  </ul>
  
  <p>Once the error occurs, MathJAX is in a bad state and will not function until entirely reloaded (e.g., via a page reload).</p>
  
  <p>It seems like the easiest solution to this problem would be to clear the MathJAX Typeset queue before loading new math via AJAX, but I can find no method in the MathJAX API that clears the Typeset queue.</p>
  
  <p>Here's a stripped-down version of the function (using jQuery syntax) I'm using:</p>
  
  <pre><code>window.loadNewMath = function() {
      // I want to clear the MathJAX Typeset queue before making the AJAX call
  
      $.ajax({
          dataType: "json",
          type: "POST",
          url: "/getNewMath",
          data: [],
          success: function(data) {
              if (data['success']) {
                  // load math into DOM
                  $("#math-panel").html(data.new_math);
                  MathJax.Hub.Queue(["Typeset", MathJax.Hub, 'math-panel']);
              } else {
                  $("#math-panel").html('oops. there was a database error');
              }
          },
          error: function(data) {
              $("#math-panel").html('oops. there was an ajax error');
          }
      })
  }
  </code></pre>
  
  <p>This scenario seems like a common use case, so I hope someone can recommend a way of avoiding this error.</p>