Ben Hernandez
Ben Hernandez

Reputation: 857

Using MathJax to add element to the DOM?

I am trying to dynamically create an element then do some processing on it. I was trying to use MathJax on that newly created element but I can't pull MathJax.Hub.getAllJax on it.

I typed this in the console to test things out: (MathOutput1 is defined in the HTML)

MathJax.HTML.addElement(document.body, "div", {id: "blah"}, ['` `']);
<div id=​"blah">​` `​</div>​
MathJax.Hub.getAllJax("blah");
[]
MathJax.Hub.getAllJax("MathOutput1")
[Object]

Is there a way I can dynamically create an element that I can act on?

I did confirm that the div element blah was added to the dom (at least according to chrome) ""

Thanks :)

Upvotes: 2

Views: 800

Answers (1)

rphv
rphv

Reputation: 5537

The problem here is that MathJax operates asynchronously, and you're trying to access the new element before the MathJax.Hub routines are fully finished.

To get around this, you can put your call to MathJax.Hub.getAllJax() in a callback function on the Hub's callback queue:

function showBlahElement () {
    console.log(MathJax.Hub.getAllJax("blah"));
}

MathJax.HTML.addElement(document.body, "div", {id: "blah"}, ['$$a=b$$']);
MathJax.Hub.Queue(showBlahElement);

Or, you can register a signal listener that will get triggered whenever a certain event happens (in this case, whenever new math is typeset):

MathJax.Hub.Register.MessageHook("New Math", function (message) {
  console.log(MathJax.Hub.getAllJax("blah"));
});

MathJax.HTML.addElement(document.body, "div", {id: "blah"}, ['$$a=b$$']);

For more information, see the API docs.

Upvotes: 2

Related Questions