I’ve been using jQuery to create HTML elements and then adding them to an XML document, like this:
var doc = $($.parseXML('<?xml version="1.0" encoding="UTF-8"?><root/>'));
var docRoot = doc.find("root");
var childEl = $("<child>");
docRoot.append(childEl);
var imageEl = $("<image>");
docRoot.append(imageEl);
var xmlString = doc.context.xml ||
new XMLSerializer().serializeToString(doc.context);
$("#xml").text(xmlString);
This is the output (on Chrome 24):
<?xml version="1.0" encoding="UTF-8"?>
<root>
<child xmlns="http://www.w3.org/1999/xhtml"></child>
<img xmlns="http://www.w3.org/1999/xhtml" />
</root>
Here’s the JSFiddle link. Unfortunately, I’m having two problems.
-
When I try to create an element with the name like
child, it correctly creates a element with the tagNamechild. However, if I use the nameimage, for some reason jQuery thinks I want to make animgelement. How do I stop jQuery from doing this? -
All child elements get the attribute
xmlns="http://www.w3.org/1999/xhtml"added automatically, even though the document I’m generated is not an XHTML document. How do I stop this from happening?
Update:
The image tagName problem appears to be a problem with the DOM, not jQuery, as this code demonstrates:
var el = document.createElement("image");
$("#output").append(el.tagName); // Outputs "IMG"
imageis a synonym forimg.document.createElement('image')actually creates animgelement, like I explained in this question.Still, all hope is not lost. When you pass an HTML/XML string to
jQuery, the second argument is the owner document of the elements to be parsed.Since you already created an XML document object in your first step, I believe that
will use the
createElementmethod of the XML document and create the correct element.Note: Internally, jQuery uses
jQuery.parseHTMLwhen passed such a string, so this method might not always work. It looks like though that jQuery consistently uses the passed in document (context). It should certainly work for single tags.Safer (and maybe easier?) might be to just use: