jQuery won't parse xml with nodes called option

Update

jQuery has this method built-in now. You can use

$.parseXML("..")

to construct the XML DOM from a string.


jQuery relies on the HTML DOM using innerHTML to parse the document which can have unreliable results when tag names collide with those in HTML.

Instead, you can use a proper XML parser to first parse the document, and then use jQuery for querying. The method below will parse a valid XML document in a cross-browser fashion:

// http://www.w3schools.com/dom/dom_parser.asp
function parseXML(text) {
    var doc;

    if(window.DOMParser) {
        var parser = new DOMParser();
        doc = parser.parseFromString(text, "text/xml");
    }
    else if(window.ActiveXObject) {
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.async = "false";
        doc.loadXML(text);
    }
    else {
        throw new Error("Cannot parse XML");
    }

    return doc;
}

Once the XML DOM is constructed, jQuery can be used as normal - http://jsfiddle.net/Rz7Uv/

var text = "<root><option>cow</option><option>squirrel</option></root>";
var xml = parseXML(text);
$(xml).find("option"); // selects <option>cow</option>, <option>squirrel</option>

This is probably some special handling for the HTML <option> element, but I can't find that in the source.


On line 4448 of the unminified source for 1.4.2 is the culprit:

// ( div = a div node )
// ( elem = the xml you've passed to it )

div.innerHTML = wrap[1] + elem + wrap[2]; 

Consider this code:

var d = document.createElement('div');
d.innerHTML = "<foo><option>bar</option><b>blah</b></foo>";

alert(d.innerHTML); // <foo>bar<b>blah</b></foo>

// tested on Firefox 3.6

So, don't ask me why exactly, but it looks like something in the way the DOM handles it, not necessarily jQuery's fault.

Perhaps just use a different node name?