Search code examples
javascripthtmldommathjax

How do I append a mathJax paragraph with DOM Maniplunation?


I've been trying to wrap around my head the documentation on this page https://docs.mathjax.org/en/v1.0/typeset.html but I can't seem to get it work.

It works just fine if I type in the expression on a static HTML page but if I try to append a paragraph this way:

let para = document.createElement("P");
let testExp =  document.createTextNode("$$ testexpression \cdot \frac{2}{3}$$");
para.appendChild(testExp);
document.getElementById("sampleDoc").append(para);

the expression just appears as a String. I'm aware that people have asked similar things before but I couldn't find something that helps me.

I'd also be interested if someone could why it does not work this way but works just fine if I write the same expression as a paragraph on a static HTML page

Kind regards


Solution

  • createTextNode only creates a plain text node. You’re not calling the typesetting function in your code, so it never changes. You can add this line:

    MathJax.Hub.Queue(["Typeset", MathJax.Hub, "sampleDoc"]);
    

    This queues MathJax’s typesetting function, as explained in the documentation. It goes through your document and makes the necessary changes. The last parameter is the ID of a specific element to typeset. You can leave it out to typeset the entire document.

    You don’t need to do any of this on a static page because MathJax automatically runs the typesetting function when it loads.