I am trying to render some maths equations in MathJax via JavaScript but its not working well for all formulas.
<html>
<head>
<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-MML-AM_CHTML"
async>
</script>
</head>
<body>
<div id="formula"> </div>
<script>
function render() {
document.getElementById('formula').innerHTML = "$$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$"
MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
};
render();
</script>
</body>
</html>
However it works pretty fine directly e.g.
<div id="formula"> $$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$ </div>
Finally I have found the solution. The backslashes need to be doubled in JavaScript text string literals (since the backslash is a special character in strings). So it should be "$$ x = {-b \\pm \\sqrt{b^2-4ac} \\over 2a} $$ " to get the same result as the original HTML.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With