Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery creates incorrect element for image tag

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.

  1. 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?

  2. 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"
like image 893
cdmckay Avatar asked Oct 05 '22 23:10

cdmckay


1 Answers

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'));
like image 159
Felix Kling Avatar answered Oct 13 '22 10:10

Felix Kling