Search code examples
javascriptnode.jsmathjaxkatex

Render math with KaTeX in the browser


I am using KaTeX to render math in the browser.

Right now I am using something like

document.getElementById('el').innerHTML = function () {
  const span = document.createElement('span');
  katex.render('2+\frac{1}{x}', span);
  return span.innerHTML;
});

but it seems really stupid that I have to apply it to an element, and then take the html from this element and insert in my string.

I have looked through the KaTeX documentation, but I cannot find anything to help me just rendering some text directly in the browser with something like katex.render('2+3+4').


Solution

  • I don't know if you're still looking for an answer but maybe this will be helpful.

    First, I link to katex.min.js and katex.min.css from a cdn.

    I wrap everything I want rendered in katex inside span tags and give them the class 'math'

    For example:

    <span class='math'>2+\frac{1}{x}</span>
    

    Then inside a pair of script tags I include something like this:

    var math = document.getElementsByClassName('math');
    for (var i = 0; i < math.length; i++) {
      katex.render(math[i].textContent, math[i]);
    }
    

    So as long as I write my math text inside an element with the class math, it gets rendered by katex.

    EDIT: We should use textContent instead of innerHTML. I've run into issues using innerHTML. See using katex, '&' alignment symbol displays as 'amp;'