views:

23

answers:

3

I'm using jQuery to parse XML which is retrieved via ajax, however I have found a problem/bug with using the actual XML input.

Consider the following example:

var $line = $('<example dir="value">Example Text</example>'), dir = $line.attr("dir");
console.info("dir: ", dir);

This example should return 'value' instead it returns an empty string. Tried the above code with a different attribute name and it returns the correct value.

Is 'dir' an invalid attribute? Or is this a bug in jQuery? Just wondering...

A: 

because i dont think it gets parsed, try this

var $line = $('<example></example>').attr('dir','value').value('Example Text');
RobertPitt
Tried the above with a slight difference: `var $line = $('<example></example>').attr('dir','value').val('Example Text');`But the result is the same. I Know that the example I give is being parsed because changing to: `var $line = $('<example direction="value">Example Text</example>')` would work. However I cannot change the ajax retrieved XML so have to stick with the 'dir' attribute.
vitorhsb
+1  A: 

$(markup) parses as HTML, not XML, giving you an HTMLUnknownElement with tagName example. dir is an existing HTML attribute which may only have the values rtl or ltr. Anything else is ignored, which is why the custom attribute isn't readable under the DOM property dir.

(Contrary to what you might expect from the name, jQuery's attr() method actually usually represents DOM property access and not HTML attribute access, even though it allows the HTML attribute names to be used as aliases.)

You may have further problems in IE which doesn't much like custom elements being dropped into HTML.

Getting a browser to parse XML isn't quite as simple as you might think. Having an XML document returned by XMLHttpRequest (ajax()) works everywhere, so if you can, move the XML into an AJAX response.

Otherwise, getting an XML parser to read a string isn't the same on all browsers (and older browsers can't do it at all). On IE you have to use a new ActiveXObject('Microsoft.XMLDOM'); on other browsers you often get a new DOMParser(); failing that, you can try to document.implementation.createDocument().loadXML().

bobince
+1  A: 

dir = $line.get(0).getAttribute("dir") works just fine.

Going to post this issue in the jQuery discussion page.

vitorhsb