Search code examples
javascriptjqueryxmldommathml

Insert MathML dynamically with jQuery


I scripted a nasty little javascript function, which creates a MathML Matrix DOM. My problem is that when I insert the DOM with jQuery's append(MathMLDOM); it isn't being displayed correctly. But when i copy paste the generated XML and insert it manually into a HTML document it displays just fine. Why doesn't append work and is there some way to dynamically insert MathML DOM?

regards


Solution

  • Yes, you need the namespace, it needs to be given at element creation. The createElementNS() method of the document object accomplishes this:

    document.createElementNS("http://www.w3.org/1998/Math/MathML", "element");
    

    where "element" is a string, like "mo", "mfrac", "math", etc. You can wrap it in a function that inserts the correct namespace. It works in Firefox, anyway.

    var mathml = function(el) {
        return document.createElementNS("http://www.w3.org/1998/Math/MathML", el);
    };
    

    You can create a jQuery object from it afterwards:

    $mi1 = $( mathml("mi") ).text(a);
    $mn1 = $( mathml("mn") ).text(2);
    $term1 = $( mathml("msup") ).append($mi1).append($mn1);
    

    would give you a $term1 jQuery object with content a2.