jQuery is an HTML-based library and has limited capabilities for dealing with XML (or cross-document scripting in general).
Some methods will work: find()
and text()
against XML are generally OK. But when you return a markup string like <b>foo</b>
jQuery will use that as HTML content, and try to write it to an element's innerHTML
. But an XML document isn't HTML, and accordingly doesn't support innerHTML
, so jQuery fails.
In any case, you don't want to take an element's text()
and use it verbatim as markup. What if that text contains <
or &
characters? That would break markup and potentially give you cross-site-scripting vulnerabilities. Don't prepare HTML using naïve string-slinging.
Instead, use DOM-style methods. jQuery methods like replace()
would do it, however you can't use the simple replace('<b>')
because, again, jQuery would take that '<b>'
and turn it into an HTML bold element owned by the current HTML document, then try to insert that HTML element into the XML document, which won't work. Instead, you'll need to create the element manually using the XML DOM:
$(xml).find("foo").each(function() {
var b= xml.createElement('b');
this.parentNode.replaceChild(b, this);
while (this.firstChild)
b.appendChild(this.firstChild);
});
This changes the XML document. But this doesn't really seem to help you if what you're trying to do is convert an XML document into usable HTML. Using a serialiser (browser-dependent) to convert back to XML markup would give markup that isn't necessarily HTML-compatible (eg. empty tags might self-close).
To import XML elements reliably into HTML is probably best done manually. (There is importNode
, but IE doesn't support it.) eg.:
function xmlToDocument(node, dest) {
if (node.nodeType===1) {
// Create HTML element from XML element. Change name if 'foo'.
//
var tag= node.tagName.toLowerCase()==='foo'? 'b' : node.tagName;
var el= document.createElement(tag);
dest.appendChild(el);
// Copy attributes
//
for (var attri= node.attributes.length; attri-->0;) {
var attr= node.attributes[attri];
el.setAttribute(attr.name, attr.value);
}
// Copy element contents
//
for (var child= node.firstChild; child!==null; child= child.nextSibling)
xmlToDocument(child, el);
}
else if (node.nodeType===3)
dest.appendChild(document.createTextNode(node.));
}
You know... it might be easier to just return some HTML markup in a JSON object.