Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render MathJax through JavaScript not working well

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>
like image 655
Shahzad Akram Avatar asked Oct 29 '25 13:10

Shahzad Akram


1 Answers

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.

like image 58
Shahzad Akram Avatar answered Nov 01 '25 03:11

Shahzad Akram



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!