Skip to content

Instantly share code, notes, and snippets.

@sdiehl
Created December 16, 2010 21:46
Show Gist options
  • Save sdiehl/744083 to your computer and use it in GitHub Desktop.
Save sdiehl/744083 to your computer and use it in GitHub Desktop.
jquery-mathml
convertMath = function (node) {
try {
if (node.nodeType == 1) {
var newnode = document.createElementNS("http://www.w3.org/1998/Math/MathML", node.nodeName.toLowerCase());
for (var i = 0; i < node.attributes.length; i++)
newnode.setAttribute(node.attributes[i].nodeName, node.attributes[i].nodeValue);
for (var i = 0; i < node.childNodes.length; i++) {
var st = node.childNodes[i].nodeValue;
if (st == null || st.slice(0, 1) != " " && st.slice(0, 1) != "\n") newnode.appendChild(this.convertMath(node.childNodes[i]));
}
return newnode;
} else {
return node;
}
} catch (e) {}
}
replaceWith: function (value) {
if (this[0] && this[0].parentNode) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if (jQuery.isFunction(value)) {
return this.each(function (i) {
var self = jQuery(this),
old = self.html();
self.replaceWith(value.call(this, i, old));
});
}
if ((typeof value !== "string")) {
if (!this.isMath()) {
value = jQuery(value).detach();
}
}
return this.each(function () {
var next = this.nextSibling,
parent = this.parentNode;
// Graft MathML XML
if (this.namespaceURI.indexOf("MathML") > -1) {
mathmlfrag = (new DOMParser()).parseFromString(value, 'text/xml');
if (mathmlfrag.documentElement.nodeName=="parsererror") {
var errs = mathmlfrag.documentElement.childNodes[0].nodeValue;
errs = errs.replace(/</g, "&lt;");
console.log(errs);
}
newml = convertMath(mathmlfrag.childNodes[0]);
parent.replaceChild(newml, this);
return newml;
}
jQuery(this).remove();
if (next) {
jQuery(next).before(value);
} else {
jQuery(parent).append(value);
}
});
} else {
return this.pushStack(jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value);
}
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value );
}
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment