Mathjax plug in with javascript does not identify inline math expressions

Viewed 251

This is my code to implement Mathjax.

    <head>

        <script src='https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>

        <script type="text/x-mathjax-config">
          MathJax.Hub.Config({
            tex2jax: { inlineMath: [['$', '$']] },
            elements: ['math']
          });
        </script>

    </head>

This is my code to add another math expression into the html

function dumpElement(blockIdentifier, questionNumber, data){
    document.getElementById(blockIdentifier).innerHTML += `<p style= "float:left; left:0%;">` + (questionNumber + ')') + `</p> 
                                                            <p id = "math">` + data + `</p> <br><br><br><br>`;
}

After the page initially loads and this function is invoked, I cannot get the "data," a latex encoded string, to be displayed properly. For example, here is an element I copied using the inspect element.

<p id="math">$\frac{37}{40}$</p>

What's EVEN MORE INTERESTING is that the following html tag is statically typed into the html (that is, it will be displayed before function dumpElement() ) and properly displays!

<p id="math">$-\frac{2}{3}$</p>

What should I do to get the dynamically printed html tags to display correctly? Thanks.

1 Answers

Try to change a bit your MathJax config options. Maybe the tex2jax would be enough:

<script src='https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML'></script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: { inlineMath: [['$', '$']] }
  });
</script>

If it's needed, use unique ID's for elements:

<p id="math-1">$\frac{37}{40}$</p>

<p id="math-2">$1-\frac{2}{3}$</p>

<div id="some-unique-id">Some text...</div>

Also I would try to change a JavaScrtipt code as well:

function dumpElement(blockIdentifier, questionNumber, data) {
    const wrapperElement = document.getElementById(blockIdentifier);
    
    let htmlText = `<p style="float: left; left: 0%;">${questionNumber})</p>`;
    htmlText += `<p id="math-{questionNumber}">${data}</p><br><br><br><br>`;
  
    wrapperElement.innerHTML += htmlText;
}

dumpElement('some-unique-id', '3', '$4^2-\\frac{37}{40}$');

Demo - https://codepen.io/vyspiansky/pen/yLOVeMe?editors=1010

Related