3

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').

Jamgreen
  • 10,329
  • 29
  • 113
  • 224
  • Possible duplicate of https://stackoverflow.com/questions/39930756/render-tex-with-katex-or-mathjax – v7d8dpo4 Oct 10 '16 at 15:37
  • 3
    Why not simply `katex.render('2+\\frac{1}{x}', document.getElementById('el'));`? – MvG Jun 22 '17 at 00:20

2 Answers2

4

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;'

dactyrafficle
  • 838
  • 8
  • 18
3

Use KaTeX's auto-render extension, which will let you add your KaTeX directly to the HTML with a delimiter like $$ and then render it all at once:

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/katex.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.7.1/contrib/auto-render.min.js"></script>
</head>
<body>
    <div id="el"><span>$$2+\frac{1}{x}$$</span></div>
    <script>
        renderMathInElement(document.body);
    </script>
</body>
</html>
Vincent
  • 2,689
  • 3
  • 24
  • 40
  • 3
    How can I use this extension with Node? npm install katex doesnt include this extension – raj Sep 28 '18 at 22:14