Reputation: 11059
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')
.
Upvotes: 3
Views: 5392
Reputation: 868
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;'
Upvotes: 4
Reputation: 2787
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>
Upvotes: 3