jQuery creates incorrect element for image tag

javascript, jquery, xml

Solution

`image` is a synonym for `img`. `document.createElement('image')` actually creates an `img` element, 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

var imageEl = $("<image />", doc[0]);

will use the `createElement` method of the XML document and create the correct element.

Note: Internally, jQuery uses `jQuery.parseHTML` when 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:

var imgeEl = $(doc[0].createElement('image'));

Problem

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 tagName `child`. However, if I use the name `image`, for some reason jQuery thinks I want to make an `img` element. 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" ```

Original source

Related problems